创建并将值从View包分配回MVC中的文本框

时间:2014-10-09 01:12:53

标签: asp.net-mvc viewbag

我必须从MVC中的viewbag属性创建一个文本框。我可以像@Html.TextBox("Comments", (string)ViewBag.Comments)那样进行映射,但是当页面发布到服务器时,我该如何阅读它。它没有填充viewbag属性。我对MVC很新,所以也许完全不了解这个概念。

由于

1 个答案:

答案 0 :(得分:1)

您的ViewBag不会从您的视图中更新,这不是从表单获取数据的方法。相反,您应该使用强类型模型绑定来从Action方法中读取数据,或者只需检查Forms数据中的键即可。我告诉你两个例子:

示例1:强类型模型绑定。

    [HttpPost]
    public ActionResult MyAction(string comments)
    {
        // the Comment from the text box.

        return View();
    }

示例2:从已发布数据中读取:

    [HttpPost]
    public ActionResult MyAction()
    {
        // the Comment from the text box.
        string comments = Request.Form["comments"];

        return View();
    }

我希望您能使用示例1.

无论如何,最佳做法是将View与Model类绑定,并使用HtmlHelper生成如下文本框:

Html.EditorFor(model => model.Comments)

Model类包含名为Comments的属性。

并且您的action方法应该接受与参数相同的Model类型。这是一个例子:

    [HttpPost]
    public ActionResult MyAction(MyModel model)
    {
        string comments = model.Comments;

    }

您应该将View绑定到MyModel类型的模型。

我可以理解,因为你是MVC的新手,现在可能没有明确的意义,因此,我建议你查看一些基本的MVC教程。您可以从这里开始:http://www.asp.net/mvc/tutorials