MVC视图渲染不遵循传递给视图模型的数据。

3

我正在尝试创建一个MVC操作方法,允许用户逐步查看一系列数据库记录。每次用户提交更新时,它将被提交到数据库并检索和呈现一个新的记录,以供审核。

然而,我的MVC视图似乎将来自提交的视图模型和由于数据库查询而创建的新视图模型的数据组合在一起。当视图仅呈现视图模型中的属性值时,它正确地使用那些传递给它的视图模型实例中的值,但是当它将HTML表单控件绑定到视图模型属性时,它使用提交的视图模型中的值。这意味着单个视图能够显示单个视图模型实例上某个属性的两个不同值:

enter image description here

这里是操作方法的非常简化版本...

public ActionResult Index(MyViewModel model)
{
    if (ModelState.IsValid)
    {
        // Write the posted model data to the repository
        // ...

        // Retrieve a new entity for the user to work on
        var alternate = new MyViewModel { Name = "New Name" };

        return View(alternate);
    }

    return View(model);
}

... and the view model ...

public class MyViewModel
{
    [Required]
    public string Name { get; set; }
}

...而上面的图片所使用的视图...

@model Mvc4TestApplication.ViewModels.MyViewModel

Name: @Model.Name
@using (Html.BeginForm())
{
    @Html.LabelFor(model => model.Name)
    @Html.TextBoxFor(model => model.Name)
    <input type="submit" value="Submit"/>
}

看起来我误解了MVC视图发现其模型数据的方式。是否有一些替代语法,我应该使用它来明确告诉视图将其表单控件绑定到传递给它的视图模型?

谢谢,

Tim.

1个回答

4
尝试清除ModelState。html帮助程序正在使用ModelState获取值。
ModelState.Clear();

在返回视图之前

非常好的答案。感谢您解决我的问题。 - Tim Coulter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接