这个问题在这里已有答案:
我有一个包含一些字段的View,我在Controller中添加了模型状态验证,根据从下拉列表中选择的值检查2个特定字段是否为空。
这是我的代码进行验证:
public ActionResult Create(Fund fund)
{
if (fund.FundTypeId == 4)
{
if (string.IsNullOrEmpty(fund.AccountType))
{
ModelState.AddModelError("AccountType", "Account Type required");
}
if (string.IsNullOrEmpty(fund.FilePath))
{
ModelState.AddModelError("FilePath", "File Path required");
}
}
}
在这里,我的代码检查模型状态以查看它是否有效。它正确显示模型状态为false并且不执行插入和重定向。但是,我无法使用基金模型作为参数返回当前视图,以正确显示导致错误的字段旁边的错误。
if (ModelState.IsValid)
{
// Perform the insert and redirect to Index page
}
// Need to have this view reflect the errors...
return View(fund);
我收到此错误:
传递到字典中的模型项的类型为“Fund”,但此字典需要“System.Web.Mvc.HandleErrorInfo”类型的模型项。
更新:
基于我的问题的“重复”,我必须将错误的模型从我的Controller传递到我的View,并且我的View必须有一个“System.Web.Mvc.HandleErrorInfo”模型,但肯定不是这样的。
我没有将模型从视图传递到部分视图,也没有在布局文件中声明模型,所以我可以将其排除在外。
我还可以确认我的视图和控制器使用相同的模型类型。
@using FundOfFunds_MVC.Models
@model Bank.Sec.Framework.Fund
@{
ViewBag.Title = "Create New FoF Fund";
var fundTypeModel = ViewData["FundType"] as FundTypeModel;
}
更新:
发生的事情是在模型状态添加错误之后,它会在Fund Controller中触发一个OnException方法,然后在基本控制器中调用它继承的OnException方法:
public class BaseController : Controller
{
private static readonly ILog databaseLogger = LogManager.GetLogger("DatabaseLogger");
protected override void OnException(ExceptionContext filterContext)
{
GlobalContext.Properties["PageName"] = filterContext.RouteData.Values["controller"];
GlobalContext.Properties["FunctionName"] = filterContext.RouteData.Values["action"];
databaseLogger.Error("MVC Controller Error", filterContext.Exception);
base.OnException(filterContext);
filterContext.ExceptionHandled = true;
this.View("Error").ExecuteResult(this.ControllerContext);
}
}
使用“错误”视图的最后一行是罪魁祸首。这是由人们设计的代码,这些代码在MVC中不是很流畅,所以我正在尽力纠正这个问题而不重新发明轮子。
看来您的视图是强类型的,并且您使用@model Fund
作为此视图的模型。
像往常一样继续返回fund
模型,但是如果要在视图中显示错误,则必须在视图中添加以下行:
@Html.ValidationMessage("keyName")
只需将密钥的名称替换为keyName
,例如AccountType或FilePath。