MVC 3无法将字符串作为View的模型传递?

Ton*_*ony 64 asp.net-mvc asp.net-mvc-routing asp.net-mvc-3

传递给View的模型有一个奇怪的问题

调节器

[Authorize]
public ActionResult Sth()
{
    return View("~/Views/Sth/Sth.cshtml", "abc");
}
Run Code Online (Sandbox Code Playgroud)

视图

@model string

@{
    ViewBag.Title = "lorem";
    Layout = "~/Views/Shared/Default.cshtml";
}
Run Code Online (Sandbox Code Playgroud)

错误消息

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
Run Code Online (Sandbox Code Playgroud)

为什么我不能将简单的字符串作为模型传递?

nem*_*esv 112

是的,如果你正在使用正确的过载,你可以:

return View("~/Views/Sth/Sth.cshtml" /* view name*/, 
            null /* master name */,  
            "abc" /* model */);
Run Code Online (Sandbox Code Playgroud)

  • 替代解决方案:`return View("〜/ Views/Sth/Sth.cshtml",model:"abc")` (21认同)
  • 另一个解决方案:返回View("〜/ Views/Sth/Sth.cshtml",(object)"abc") (2认同)

小智 86

如果使用命名参数,则可以跳过完全给出第一个参数的需要

return View(model:"abc");
Run Code Online (Sandbox Code Playgroud)

要么

return View(viewName:"~/Views/Sth/Sth.cshtml", model:"abc");
Run Code Online (Sandbox Code Playgroud)

也将达到目的.


gdo*_*ica 17

你的意思是这个View重载:

protected internal ViewResult View(string viewName, Object model)
Run Code Online (Sandbox Code Playgroud)

MVC对此重载感到困惑:

protected internal ViewResult View(string viewName, string masterName)
Run Code Online (Sandbox Code Playgroud)

使用此重载:

protected internal virtual ViewResult View(string viewName, string masterName,
                                           Object model)
Run Code Online (Sandbox Code Playgroud)

这条路:

return View("~/Views/Sth/Sth.cshtml", null , "abc");
Run Code Online (Sandbox Code Playgroud)

顺便说一下,你可以使用这个:

return View("Sth", null, "abc");
Run Code Online (Sandbox Code Playgroud)

MSDN上的重载分辨率

  • @Tony.你的意思是`method`而不是构造函数.并且`Overload resolution`得到了错误的方法(对你来说......) (2认同)

Ale*_*sko 5

如果为前两个参数传递null,它也可以工作:

return View(null, null, "abc");
Run Code Online (Sandbox Code Playgroud)