在ASP.NET中,将字符串作为视图的参数传递



我很难在谷歌上搜索到这个,但我找不到我的问题,我觉得很奇怪,因为看起来这应该是非常简单的事情(也许我使用了糟糕的关键词(。。。

无论如何,我有一个ASP.NET应用程序,我想将一个字符串参数传递给cshtml视图。

从我的index.cshtml我传递我想要的参数:

<td>
@Html.ActionLink("Crear saludo", "Create", new { nombreSeguidor = item })
</td>

这是我迷失的地方。。。它正确地接收了参数,但我无法使用Create.cshtml.上的字符串

// GET: Saludos/Create
public ActionResult Create(string nombreSeguidor)
{
ViewBag.nombreSeguidor = nombreSeguidor; //This is my try on achieving the behaviour I want
ViewBag.Seguidores_Id = new SelectList(_repositorioSeguidores.DameTodo(), "Id", "NombreTwitch");
return View();
}

它似乎正确地接收到Seguidores_Id,但不是我的新参数(ViewBag.Seguidores_Id是由Visual Automatically创建的(

提前感谢

编辑:

回复时间:

第一个答案似乎是我在寻找什么,但现在我有了其他问题。

我在这个视图中的意图是用模型创建一个项目,但其中一些变量将自动创建。这是我的型号:

public int Id { get; set; }
public string Saludo { get; set; }
public string CreadoPor { get; set; }
public Nullable<int> Seguidores_Id { get; set; }

Id将自动设置CreadoPor如果以这种方式创建,将是一个唯一的字符串(始终相同(;并且Seguidores_ Id将取决于参数";nombreSeguidor";我们已经通过了。

因此,在这个视图中,我唯一想编辑的变量是Saludo

如何填充其他变量?直到现在,我一直在使用这个自动生成的代码:

@model string
@*@model TwitchWebApi.Models.Saludos*@
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Saludos</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@*@Html.HiddenFor(model => model.Seguidores_Id)*@
<p>
Crear saludo para @Model
</p>
<div class="form-group">
@Html.LabelFor(model => model.Saludo, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Saludo, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Saludo, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CreadoPor, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.CreadoPor, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.CreadoPor, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Seguidores_Id, "Seguidores_Id", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Seguidores_Id", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Seguidores_Id, "", new { @class = "text-danger" })
</div>
</div>

如果您想将字符串参数从public ActionResult Create(string nombreSeguidor)操作方法传递到Create.cshtml视图,可以如下所示:

// GET: Saludos/Create
public ActionResult Create(string nombreSeguidor)
{   
ViewBag.Seguidores_Id = new SelectList(_repositorioSeguidores.DameTodo(), "Id", "NombreTwitch");
return View((object)nombreSeguidor);
}

Create.cshtml:中

@model string
<!DOCTYPE html>
<html>
<body>
<div>
The passed string: @Model
</div>
</body>
</html>

甚至优选使用强类型视图而不是使用ViewDataViewBag

最新更新