这是我的场景。
创建了两个具有共同属性名称的模型
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 }
在返回看起来像这样的视图的操作(例如索引)中使用 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 不同的东西”,如测试操作中设置的那样。但事实证明,使用 Html 扩展(Html.TextBoxFor、Html.HiddenFor 等)的那些具有发布到测试操作的 Property1 值。例如,如果我将“多么惊喜”(SimpleModel1 的 Property1)发布到测试操作,SimpleModel2 的 Property1 的值也是“多么惊喜”,无论我将其设置为什么。
我不知道发生了什么。对我来说似乎是一个错误。有谁有想法吗?