MVC将模型传递到视图

7

我的Index.cshtml

@model ReportGenerator.WebUI.Models.ReportViewModel
@Html.TextBoxFor(m => m.report.FileName, new { @class = "form-control", id = "FileName" })

我的控制器

public ActionResult Index(ReportViewModel model)
{
    ...some stuff
    model.report = new Report();
    model.report.FileName = "INDEX";
    return View(model);
}

public ActionResult fillFields(ReportViewModel _model)
{
    ...some stuff
    _model.report = new Report();
    _model.report.FileName = "FILL";
    return View("Index", _model);
}

当我运行我的应用程序时,TextBoxText属性被设置为“INDEX”。当我单击调用fillFields控制器操作的按钮时,TextBox仍然显示“INDEX”,而不是更改为“FILL”。
我做错了什么?为什么它不想工作?

5
你没有做错任何事情。你的 fillFields() 方法拥有一个 ReportViewModel 参数,因此当方法被初始化时,它的值会被添加到 ModelState 中。当你返回视图后,你的 TextBoxFor() 方法使用 ModelState 中的值(而不是模型属性)来设置文本框的值。这种行为的原因在这里有解释。正确的方法是遵循 PRG 模式。 - user3559349
2
不要使用 ModelState.Clear()。遵循PRG模式并进行重定向! - user3559349
2
你的 Index() 方法不应该有一个名为 ReportViewModel model 的参数(它可能会因为多种原因而失败,并且会创建一个丑陋的查询字符串)。虽然你的意图不是很清楚,但最好的猜测是应该使用 public ActionResult Index(string fileName),然后初始化你的模型并设置 FileName 属性。在 POST 方法中,使用 return RedirectToAction("Index", new { fileName = "FILL" }); - user3559349
1
是的,但是 (1) 如果对象包含复杂对象或集合属性,则会失败 (2) 您很容易超出查询字符串限制并抛出异常 (3) 它会创建一个丑陋的查询字符串。 - user3559349
1
Mihir Kale已经添加了一个答案。你可以接受它 :) - user3559349
显示剩余8条评论
1个回答

1

在上面的评论中,@StephenMuecke已经正确回答了这个问题。

你没有做错任何事情。你的fillFields()方法有一个ReportViewModel参数,所以当方法被初始化时,它的值会被添加到ModelState中。当你返回视图时,你的TextBoxFor()方法使用ModelState中的值(而不是模型属性)来设置文本框的值。原因在这里解释。正确的方法是遵循PRG模式 -


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