【问题标题】:MVC pass model to viewMVC 传递模型来查看
【发布时间】:2016-01-01 21:17:41
【问题描述】:

我的索引.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);
}

当我运行我的应用程序时,TextBox Text 属性设置为“INDEX”。此外,当我单击调用 fillFields 控制器操作的按钮时,TextBox 仍显示“索引”,它不会更改为“填充”。

我做错了什么?为什么它不想工作?

【问题讨论】:

  • 你没有做错什么。你的fillFields() 方法有一个参数ReportViewModel,所以当方法初始化时它的值被添加到ModelState。当您返回视图时,您的 TextBoxFor() 方法使用来自 ModelState 的值(不是模型属性)来设置文本框的值。原因在here 进行了解释。正确的做法是遵循 PRG 模式
  • 不要使用ModelState.Clear()。遵循 PRG 模式并重定向!
  • 你的 Index() 不应该有参数 ReportViewModel model (它可能由于多种原因而失败,并且它会创建一个丑陋的查询字符串)。它不是很清楚你的意图是什么,但最好的猜测是它应该是 public ActionResult Index(string fileName) 然后初始化你的模型并设置 FileName 属性。在 POST 方法中,使用return RedirectToAction("Index", new { fileName = "FILL" });
  • 是的,但是 (1) 如果对象包含复杂对象或集合的属性,它将失败 (2) 您可以轻松超过查询字符串限制并引发异常 (3) 它会创建一个丑陋的查询字符串。
  • Mihir Kale 添加了答案。你可以接受:)

标签: c# asp.net-mvc asp.net-mvc-4


【解决方案1】:

@StephenMuecke 在上面的 cmets 中正确回答了这个问题。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    • 2015-04-10
    • 1970-01-01
    • 2015-06-30
    • 2021-12-03
    相关资源
    最近更新 更多