我的模型传递给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
为什么我不能将简单字符串作为模型传递?
答案 0 :(得分:110)
是的,如果您使用正确的overload:
,则可以return View("~/Views/Sth/Sth.cshtml" /* view name*/,
null /* master name */,
"abc" /* model */);
答案 1 :(得分:82)
如果您使用命名参数,则可以跳过完全提供第一个参数的需要
return View(model:"abc");
或
return View(viewName:"~/Views/Sth/Sth.cshtml", model:"abc");
也将达到目的。
答案 2 :(得分:17)
您的意思是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");
答案 3 :(得分:5)
如果为前两个参数传递null,它也可以工作:
return View(null, null, "abc");
答案 4 :(得分:4)
如果将字符串声明为对象,它也可以工作:
object str = "abc";
return View(str);
或者:
return View("abc" as object);
答案 5 :(得分:1)
您也写得像
返回视图(型号:“ msg”);
答案 6 :(得分:0)
这似乎非常明显,但将来也许有人需要进一步澄清:
如果在您的控制器中执行以下操作:
string id = "abc";
return View(model: id);
然后,您认为需要:
@model string
为了获取值,例如:
<div>@Model</div>