这是我的情景.
- public class SimpleModel1
- {
- // Some Properties
- public string Property1 { get; set; }
- }
- public class SimpleModel2
- {
- // Some Properties
- public string Property1 { get; set; } // Same name as Property1 in SimpleModel1
- }
>在Action(例如Index)中使用SimpleModel1,返回看起来像这样的视图
- @model MvcApplication2.Models.SimpleModel1
- @{
- ViewBag.Title = "Home Page";
- }
- @using (Html.BeginForm("Test","Home",FormMethod.Post))
- {
- <label>Enter something here</label>
- @Html.TextBoxFor(m => m.Property1)
- <button type="submit">Submit</button>
- }
>将值提交给以SimpleModel1作为参数的Test操作,做一些工作,并返回一个接受SimpleModel2的视图
- public ActionResult Test(SimpleModel1 model)
- {
- SimpleModel2 newModel = new SimpleModel2();
- // Do Something
- newModel.Property1 = "Something different than model's Property1";
- return View(newModel);
- }
> Test.cshtml(Test动作返回的视图)如下:
- @model MvcApplication2.Models.SimpleModel2
- @{
- ViewBag.Title = "Test";
- }
- <h2>Test</h2>
- @* Model Propery without using HTML extension*@
- @Model.Property1
- @* Model property using HTML extension (Incorrect) *@
- @Html.TextBoxFor(m => m.Property1)
- @Html.HiddenFor(m => m.Property1)
- @Html.TextAreaFor(m => m.Property1)
- @* Correct Value *@
- <input value="@Model.Property1" />
我期望的是,Property1的所有值都将是“与模型的Property1不同的东西”,如Test Action中所设置的那样.但事实证明,使用Html扩展(Html.TextBoxFor,Html.HiddenFor等)的那些具有发布到Test Action的Property1值.例如,如果我将“What a surprise”(SimpleModel1的Property1)发布到Test Action,那么无论我将它设置为什么,SimpleModel2的Property1的值也是“多么令人惊讶”.
我不知道发生了什么事.对我来说看起来像个错误.有谁有想法吗?