2012-03-21 42 views
57

我有我的模型傳遞給視圖一個奇怪的問題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 

爲什麼我不能傳遞一個簡單的字符串作爲模型?

+1

你爲什麼使用這些相對路徑?使用這個:'View(「sth」,null,「abc」);' – gdoron 2012-03-21 10:38:27

回答

102

是的,你可以的,如果你使用的是正確overload

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

你是對的,它的工作原理。謝謝 – Tony 2012-03-21 10:26:18

+16

替代解決方案:'返回查看(「〜/ Views/Sth/Sth.cshtml」,型號:「abc」)' – fejesjoco 2014-02-13 15:04:09

+2

另一種解決方案:return View(「〜/ Views/Sth/Sth.cshtml」, ) 「ABC」) – Jas 2014-04-26 14:39:32

16

您的意思這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"); 

Overload resolution on MSDN

+1

現在我看到了,我使用了構造函數'string viewName,object model' – Tony 2012-03-21 10:27:33

+2

@Tony。我的意思是'方法'不是構造函數。並且'Overload resolution'得到了錯誤的方法(對於你...) – gdoron 2012-03-21 10:29:31

+0

即使只是將字符串類型化爲對象也可能有助於重載解析:'return View(「Sth」,(object)「abc」);'' ,但是在任何情況下調用方法'View(string,string,object)'都是明確的。 – 2012-05-21 12:57:43

68

如果使用命名參數,你可以跳過需要完全給出第一個參數

return View(model:"abc"); 

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

也將服務宗旨。

3

它也可以,如果你申報字符串作爲一個對象:

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

或者:

return View("abc" as object); 
4

,如果你的前兩個參數傳遞null它也可以工作:

return View(null, null, "abc"); 
相關問題