【问题标题】:How to update model?如何更新模型?
【发布时间】:2011-01-16 20:50:47
【问题描述】:

伙计们。 我有一个正在编辑模型的 ASP.NET MVC 页面。 在执行每个动作时,我都有一个新控制器,所以我没有得到更新的模型。 我将模型实例保存到 Session["MyModelKey"] 中。但是每次执行操作时,即使我更改了这样创建的文本框中的值,我也有未修改的实例:

@Html.LabelFor(model => model.EMail) @Html.TextBoxFor(model => model.EMail) @Html.LabelFor(model => model.Country) @Html.TextBoxFor(model => model.Country) @Html.ActionLink("MyAction", "MyController")

控制器:

public class MyController : Controller
{
    public ActionResult MyAction()
    {
       //Every time this action is executed - I have a new controller instance
       //So I have null in View.Model
       //I get Session["MyModelKey"] here, 
       //But the model instance properties are not updated 
       //even though I have updated E-mail and Country properties of the model in the UI
    }
}

那么,我怎样才能获得更新的模型?

提前致谢。

【问题讨论】:

  • 我不明白你的问题。
  • 经过编辑,带来更多的问题。

标签: asp.net asp.net-mvc-3


【解决方案1】:

无需保存到会话中,模型绑定器将在后台工作以将发布的表单值与您的模型属性相匹配。

请确保您使用提交按钮,并使用表单包装 UI 元素,以便页面发布。您的操作链接不会有相同的结果。

public class SomeFormModel
{
    public string Email { get; set; }
    public string Country { get; set; }
}

public class MyController : Controller
{
    public ActionResult MyAction()
    {
        return View();
    }

    [HttpPost]
    public ActionResult MyAction(SomeFormModel model)
    {
        return View(model);
    }
} 

【讨论】:

  • 在我的例子中模型有一个集合属性。在视图中,我为每个集合项目提供了“添加”链接和“删除”链接。所以,它对我不起作用:(
  • 是的,此示例适用于常规表单帖子。您可能需要设置一些路由并使用一些 id 作为路由路径的一部分,并且链接可以点击其他操作,执行某些操作,然后重定向回原始页面以更新视图。
【解决方案2】:

您希望将视图返回到以模型为参数的操作方法。 asp.net 模型绑定器将创建参数并根据命名约定填写属性(属性名称与输入元素名称相同)。这将为您提供用户更改的任何内容的副本。

【讨论】:

  • 没有多大帮助。仅当模型是简单类型(如 int/string/etc)时才有效。
  • 您可以发布您的型号代码吗?模型绑定器可以构建相当复杂的类型。您还可以构建自己的模型绑定器。
  • 模型是 EF 模型中的实体。您是否认为我在每次操作调用时都有一个新的控制器实例?
  • 这是一个如何将数据回发到使用模型绑定的 asp.net mvc 操作方法的示例。您需要使用 [HttpPost] 属性标记您的操作方法之一。 weblogs.asp.net/scottgu/archive/2010/01/15/…
  • 我相信这与属性无关。只有当你一直使用同一个模型对象时,它才会工作。
猜你喜欢
  • 2013-09-18
  • 1970-01-01
  • 2013-08-26
  • 1970-01-01
  • 2013-11-22
  • 2013-09-01
  • 2011-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多