6

这是我的场景。

  1. 创建了两个具有共同属性名称的模型

    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
    
    }
    
  2. 在返回看起来像这样的视图的操作(例如索引)中使用 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>
    }
    
  3. 将值提交给以 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);
    }
    
  4. 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 的值也是“多么惊喜”,无论我将其设置为什么。

我不知道发生了什么。对我来说似乎是一个错误。有谁有想法吗?

4

1 回答 1

11

执行POST时会看到此行为,因为已发布的数据保留在 ModelState 中。Property1 的值将是为此属性发布的任何值。为了查看您的新值,您需要在 ActionResult 测试中包含这行代码:

ModelState.Clear();

作为一般规则,只要记住包含这一行,以防您发布数据、修改数据并尝试在返回的视图中查看修改后的数据。

于 2012-12-19T18:16:01.870 回答