asp.net-mvc MVC 3 不能将字符串作为视图模型传递?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9802546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:48:57  来源:igfitidea点击:

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

asp.net-mvcasp.net-mvc-3asp.net-mvc-routing

提问by Tony

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

我传递给视图的模型有一个奇怪的问题

Controller

控制器

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

View

看法

@model string

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

The 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's 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 ?

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

回答by nemesv

Yes you can if you are using the right overload:

是的,如果您使用正确的重载,则可以

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

回答by nemesv

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.

也将达到目的。

回答by gdoron is supporting Monica

You meant this Viewoverload:

你的意思是这个View超载:

protected internal ViewResult View(string viewName, Object model)

MVC is confused by this overload:

MVC 被这个重载弄糊涂了:

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

MSDN 上的重载解析

回答by Alex Dresko

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

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

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

回答by Tim Mac

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

如果您将字符串声明为对象,它也可以工作:

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

Or:

或者:

return View("abc" as object);

回答by Hiren Patel

You also write like

你也这样写

return View(model: "msg");

返回视图(模型:“味精”);