MVC模式不更新 [英] MVC Model not updating

查看:104
本文介绍了MVC模式不更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该模型

class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
}

控制器动作

[HttpPost]
public ActionResult GetAddress(Address model)
{
    if (!String.IsNullOrEmpty(model.Zip))
    {
        model.City = GetCityByZip(model.Zip);
    }
    return View(model);
}

视图

<div class="formrow">
    @Html.LabelFor(model => model.City)
    @Html.TextBoxFor(model => model.City) 
    @Html.ValidationMessageFor(model => model.City)
</div>
<div class="formrow"> 
    @Html.LabelFor(model => model.State)
    @Html.DropDownListFor(model => model.State, (IEnumerable<SelectListItem>)ViewBag.States, new { style = "width:217px;" }) 
    @Html.ValidationMessageFor(model => model.State) 
</div> 
<div class="formrow">
    @Html.LabelFor(model => model.Zip)
    @Html.TextBoxFor(model => model.Zip) 
    @Html.ValidationMessageFor(model => model.Zip)
</div>

问题是,只要这个城市正在被修改,它永远不会反映在视图。在调试过程中, model.City 包含正确的值,但它并不在视图中。即使是一些如 @ Html.TextBoxFor(型号为GT =; model.City)一样简单不显示正确的 model.City 值。

The problem is whenever the city is being modified, it never gets reflected on the view. During debugging, the model.City contains the correct value but it doesn't show up on view. Even something as simple as @Html.TextBoxFor(model => model.City) doesn't display the correct model.City value.

推荐答案

HtmlHelpers在更新和恢复模型从模型的状态,并没有得到的模型值模型。为了更新和返回模型,加入这一行code在您的文章的方法:

HtmlHelpers get the model values from the model state and not the model when you update and return the model. In order to update and return the model, add this line of code in your post method:

ModelState.Clear();

或者你可以设置城市价值中的ModelState本身:

or you could set the value of city in the ModelState itself:

ModelState["City"].Value = GetCityByZip(model.Zip);

这篇关于MVC模式不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆