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

后端 未结 7 1562
忘了有多久
忘了有多久 2021-02-03 16:46

I have a strange problem with my model passed to the View

Controller

[Authorize]
public ActionResult Sth()
{
    return View(\"~/Views/S         


        
相关标签:
7条回答
  • 2021-02-03 17:09

    You also write like

    return View(model: "msg");
    
    0 讨论(0)
  • 2021-02-03 17:14

    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.

    0 讨论(0)
  • 2021-02-03 17:15

    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

    0 讨论(0)
  • 2021-02-03 17:22

    Yes you can if you are using the right overload:

    return View("~/Views/Sth/Sth.cshtml" /* view name*/, 
                null /* master name */,  
                "abc" /* model */);
    
    0 讨论(0)
  • 2021-02-03 17:28

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

    return View(null, null, "abc");
    
    0 讨论(0)
  • 2021-02-03 17:28

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

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

    Or:

    return View("abc" as object);
    
    0 讨论(0)
提交回复
热议问题