MVC 3 Can't pass string as a View's model?

六眼飞鱼酱① 提交于 2019-12-02 21:33:51

Yes you can if you are using the right overload:

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

If you use named parameters you can skip the need to give the first parameter altogether

return View(model:"abc");

or

return View(viewName:"~/Views/Sth/Sth.cshtml", model:"abc");

will also serve the purpose.

You meant this View overload:

protected internal ViewResult View(string viewName, Object model)

MVC is confused by this overload:

protected internal ViewResult View(string viewName, string masterName)

Use this overload:

protected internal virtual ViewResult View(string viewName, string masterName,
                                           Object model)

This way:

return View("~/Views/Sth/Sth.cshtml", null , "abc");

By the way, you could just use this:

return View("Sth", null, "abc");

Overload resolution on MSDN

It also works if you pass null for the first two parameters:

return View(null, null, "abc");

It also works if you declare the string as an object:

object str = "abc";
return View(str);

Or:

return View("abc" as object);

You also write like

return View(model: "msg");

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!