UpdateModel不更新我的模型

时间:2012-08-08 13:06:26

标签: asp.net-mvc razor updatemodel

我必须设置错误,因为我无法使用UpdateModel函数根据通过FormCollection传入的信息正确更新我的模型。

我的观点如下:

@model NSLM.Models.Person
@{
    ViewBag.Title = "MVC Example";
}
<h2>My MVC Model</h2>
<fieldset>
    <legend>Person</legend>
    @using(@Html.BeginForm())
    {
        <p>ID: @Html.TextBox("ID", Model.ID)</p>
        <p>Forename: @Html.TextBox("Forename", Model.Forename)</p>
        <p>Surname: @Html.TextBox("Surname", Model.Surname)</p>
        <input type="submit" value="Submit" />
    }  
</fieldset>

我的模特是:

    namespace NSLM.Models
    {
        public class Person
        {
            public int ID;
            public string Forename;
            public string Surname;
        }
    }

我的控制器是:

        [HttpPost]
        public ActionResult Details(FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here                
                Models.Person m = new Models.Person();

                // This doesn't work i.e. the model is not updated with the form values
                TryUpdateModel(m);

                // This does work 
                int.TryParse(Request.Form["ID"], out m.ID);
                m.Forename = Request.Form["Forename"];
                m.Surname = Request.Form["Surname"];

                return View(m);
            }
            catch
            {
                return View();
            }
        }

正如你可以看到我是否手动分配每个属性它工作正常,那么我没有设置什么会使模型更新表单值?

谢谢,

标记

3 个答案:

答案 0 :(得分:1)

当调用到达action方法时,任何自动模型绑定都已执行。尝试更改操作方法的输入参数以接受Person实例。在这种情况下,模型绑定器将尝试创建实例并从表单传递的值填充它。

答案 1 :(得分:1)

用模型中的属性替换字段,即:

namespace NSLM.Models
{
    public class Person
    {
        public int ID {get; set;}
        public string Forename {get; set;}
        public string Surname {get; set;}
    }
}

答案 2 :(得分:0)

试试这个:

观点:

@model NSLM.Models.Person
@{
    ViewBag.Title = "MVC Example";
}
<h2>My MVC Model</h2>
<fieldset>
    <legend>Person</legend>
    @using(@Html.BeginForm())
    {
         @Html.HiddenFor(model => model.ID)

        <p>Forename: @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </p>
        <p>Surname: @Html.EditorFor(model => model.Surname)
            @Html.ValidationMessageFor(model => model.Surname)
        </p>
        <input type="submit" value="Submit" />
    }  
</fieldset>

控制器:

[HttpPost]
public ActionResult Details(Person p)
{
    if (ModelState.IsValid)
    {
        db.Entry(p).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(p);
}