MVC 3 Can't pass a string as a view model?

I have a strange problem with my model passed to a view

controller

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

View

 @model string @{ ViewBag.Title = "lorem"; Layout = "~/Views/Shared/Default.cshtml"; } 

Error message

 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 name ? ~/Views/Shared/abc.master ~/Views/Sth/abc.cshtml ~/Views/Sth/abc.vbhtml ~/Views/Shared/abc.cshtml ~/Views/Shared/abc.vbhtml 

Why can't I pass a simple string as a model?

+56
asp.net-mvc asp.net-mvc-3 asp.net-mvc-routing
Mar 21 '12 at 10:19
source share
5 answers

Yes, if you use the right overload :

 return View("~/Views/Sth/Sth.cshtml" /* view name*/, null /* master name */, "abc" /* model */); 
+98
Mar 21 '12 at 10:23
source share

If you use named parameters, you can skip the need to give the first parameter at all

 return View(model:"abc"); 

or

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

will also serve the purpose.

+65
Jan 21 '13 at 11:39 on
source share

Did you mean 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) 

In 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

+16
Mar 21 '12 at 10:22
source share

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

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

Or:

 return View("abc" as object); 
+3
Aug 7 '13 at 17:45
source share

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

 return View(null, null, "abc"); 
+3
Nov 04 '13 at 17:53
source share



All Articles