开发者

How to update model?

guys. I have an ASP.NET MVC page where the model is being edited. On each action executing I have a new controller, so I don't get an updated model. I'm saving a model instance into Session["MyModelKey"]. But every time an action is executed, I have unmodified instance there even if I have changed values in textboxes which were created like this:

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

Controller:

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
    }
}

So, how can I get an updated model?

Thanks in advance.


No need to save to session the model binder will work behind the scenes to match the posted form values to your model properties.

Make sure you use a submit button though, and wrap the UI elements with a form so the page will post. Your action link will not have the same outcome.

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);
    }
} 


You want to pst back your view to an action method that has the model as a parameter. The asp.net model binder will create the parameter and fill in the properties based upon a naming convention (property name same as input element name). This will get you a copy of any content changed by the user.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜