Pit*_*ari 6 properties htmlextensions razor asp.net-mvc-4
这是我的情景.
创建了两个具有公共属性名称的模型
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
}
Run Code Online (Sandbox Code Playgroud)在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>
}
Run Code Online (Sandbox Code Playgroud)将值提交给将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);
}
Run Code Online (Sandbox Code Playgroud)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" />
Run Code Online (Sandbox Code Playgroud)我期望的是,Property1的所有值都将是"与模型的Property1不同的东西",如Test Action中所设置的那样.但事实证明,使用Html扩展(Html.TextBoxFor,Html.HiddenFor等)的那些具有发布到Test Action的Property1值.例如,如果我将"What a surprise"(SimpleModel1的Property1)发布到Test Action,那么无论我将它设置为什么,SimpleModel2的Property1的值也是"多么令人惊讶".
我不知道发生了什么事.对我来说看起来像个错误.有谁有想法吗?
Dmi*_*try 11
执行POST时会看到此行为,因为已发布的数据在ModelState中保留.Property1的值将是为此属性发布的值.要查看新值,您需要在ActionResult测试中包含以下代码行:
ModelState.Clear();
Run Code Online (Sandbox Code Playgroud)
作为一般规则,只需记住包含此行,以防您发布数据,修改数据并尝试在返回的视图上查看已修改的数据.
归档时间: |
|
查看次数: |
1572 次 |
最近记录: |