MVC 3无法将字符串作为View的模型传递?
我有我的模型传递给视图一个奇怪的问题MVC 3无法将字符串作为View的模型传递?
控制器
[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
为什么我不能传递一个简单的字符串作为模型?
是的,你可以的,如果你使用的是正确overload:
return View("~/Views/Sth/Sth.cshtml" /* view name*/,
null /* master name */,
"abc" /* model */);
您的意思这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");
现在我看到了,我使用了构造函数'string viewName,object model' – Tony 2012-03-21 10:27:33
@Tony。我的意思是'方法'不是构造函数。并且'Overload resolution'得到了错误的方法(对于你...) – gdoron 2012-03-21 10:29:31
即使只是将字符串类型化为对象也可能有助于重载解析:'return View(“Sth”,(object)“abc”);'' ,但是在任何情况下调用方法'View(string,string,object)'都是明确的。 – 2012-05-21 12:57:43
如果使用命名参数,你可以跳过需要完全给出第一个参数
return View(model:"abc");
或
return View(viewName:"~/Views/Sth/Sth.cshtml", model:"abc");
也将服务宗旨。
它也可以,如果你申报字符串作为一个对象:
object str = "abc";
return View(str);
或者:
return View("abc" as object);
,如果你的前两个参数传递null它也可以工作:
return View(null, null, "abc");
你为什么使用这些相对路径?使用这个:'View(“sth”,null,“abc”);' – gdoron 2012-03-21 10:38:27