MVC 3不能传递string作为视图的模型?
我有一个奇怪的问题,我的模型传递给视图
调节器
[Authorize] public ActionResult Sth() { return View("~/Views/Sth/Sth.cshtml", "abc"); }
视图
@model string @{ ViewBag.Title = "lorem"; Layout = "~/Views/Shared/Default.cshtml"; }
错误消息
The view '~/Views/Sth/Sth.cshtml' or its master was not found or no view engine supports the searched locations. The following locations were searched: ~/Views/Sth/Sth.cshtml ~/Views/Sth/abc.master //string model is threated as a possible Layout's name ? ~/Views/Shared/abc.master ~/Views/Sth/abc.cshtml ~/Views/Sth/abc.vbhtml ~/Views/Shared/abc.cshtml ~/Views/Shared/abc.vbhtml
为什么我不能传递一个简单的string作为模型?
是的,你可以如果你正在使用正确的超载 :
return View("~/Views/Sth/Sth.cshtml" /* view name*/, null /* master name */, "abc" /* model */);
如果使用命名参数,则可以省略完全给出第一个参数
return View(model:"abc");
要么
return View(viewName:"~/Views/Sth/Sth.cshtml", model:"abc");
也将达到目的。
你的意思是这个View
过载:
protected internal ViewResult View(string viewName, Object model)
MVC被这个过载所困惑:
protected internal ViewResult View(string viewName, string masterName)
使用这个过载:
protected internal virtual ViewResult View(string viewName, string masterName, Object model)
这条路:
return View("~/Views/Sth/Sth.cshtml", null , "abc");
顺便说一下,你可以使用这个:
return View("Sth", null, "abc");
在MSDN上重载parsing
如果将该string声明为对象,它也可以工作:
object str = "abc"; return View(str);
要么:
return View("abc" as object);
如果您为前两个parameter passingnull,它也可以工作:
return View(null, null, "abc");