0

我必须有一些错误的设置,因为我无法让 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();
            }
        }

正如您所看到的,如果我手动分配每个属性它工作正常,那么我没有设置什么可以让模型使用表单值更新?

谢谢,

标记

4

3 回答 3

1

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

于 2012-08-08T13:12:12.067 回答
1

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

namespace NSLM.Models
{
    public class Person
    {
        public int ID {get; set;}
        public string Forename {get; set;}
        public string Surname {get; set;}
    }
}
于 2012-08-09T06:36:55.867 回答
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);
}
于 2012-08-08T13:18:44.227 回答