如何在 MVC5 ASP.NET 中将字符串从控制器传递到视图



我有这个控制器:

public ActionResult MyController(string myString)
{
    return View((object)myString);
}

我正在尝试传递字符串以如下所示查看:

@model string
@Html.EditorFor(m => m)

我得到的值不能为空错误。我该如何解决这个问题?谢谢。

首先,我建议更改您的操作方法名称。为什么你把它命名为MyController。它应该是一个有意义的方法名称。

然后来谈谈你的问题。如果您的视图仅用于显示目的,而不是用于表单发布,则可以在viewbag中绑定字符串并在视图中呈现。

例如,在您的操作方法中,

ViewBag.MyString = myString;

在你看来,

<p>@ViewBag.MyString</p>

但是如果你想在视图中编辑你的字符串,在点击提交按钮后,它应该将值发布到服务器,然后创建一个view model,例如,

public class MyStringModel
{
  public string MyString { get; set; }
}

在你的操作方法中,

public ActionResult MyController(string myString)
{
  MyStringModel = new MyStringModel();
  MyStringModel.MyString = myString;
  return View(MyStringModel)
}

那么在你看来,

@model MyStringModel
@Html.EditorFor(m => m.MyString)

看,您需要在视图中添加@HTML.BeginFormsubmit buttonpost back字符串数据。

希望对您有所帮助。

您还可以使用具有不同信息生命周期的 ViewBag、ViewData、TempData 将信息传递到您的视图。

检查这个:

http://royalarun.blogspot.com.ar/2013/08/viewbag-viewdata-tempdata-and-view.html

在您的示例中,模型与字典相关联,因此您不能像这样直接使用属性。

对于您的示例,只需从控制器传递一个字符串,您就可以执行以下操作:

public ActionResult MyController(string myString)
{
    return View(model:myString);  
}

和 .cshtml 中(如果您使用 C#(

@model string
@{
    var text = Model;
}
@Html.EditorFor(m => text);

但我认为更好的解决方案是传递带有字符串属性的 viewMoedel @Stephen Muecke 响应预填充 Html 编辑器 Asp.net MVC

最新更新