C# 将一个简单的字符串从控制器传递给视图 MVC3
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11296634/
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
Pass a simple string from controller to a view MVC3
提问by Francis Rodgers
I know this seems pretty basic, and it should be, but I cant find out where I am going wrong. (I hve read other articles with similar titles on SO, and other resources on the web but still cant figure it out), so any help would be appreciated.
我知道这看起来很基本,应该是,但我不知道我哪里出错了。(我在 SO 上阅读了其他具有类似标题的文章,以及网络上的其他资源,但仍然无法弄清楚),因此将不胜感激。
I have a controller and in it I am setting a string variable. Now I don't mind if this takes the form of a property, an ActionResult, or a straight method. I just want a simple string that I can play with in the controller, and return it to the view.
我有一个控制器,我在其中设置了一个字符串变量。现在我不介意这是采用属性、ActionResult 还是直接方法的形式。我只想要一个可以在控制器中使用的简单字符串,然后将其返回到视图中。
Essentially what I am trying to do is list the files in a given folder. So my logic is like this:
基本上我想要做的是列出给定文件夹中的文件。所以我的逻辑是这样的:
- Find the current folder (partially successful)
Append the path to the where the files you want to located are. i.e. if my current folder is Web\ then I will append something like "Content\CSS" if I wanted to list all the CSS files for example. (I do this because I want to allow the user to dynamically change the site by selecting the css to apply). So it would look like:
CurrentPath += "Content\CSS"
I want load the file names into an array or list
- I want to pass this list to my view to render in a combo box (which is on my _Layout.cshtml).
- 找到当前文件夹(部分成功)
将路径附加到您要定位的文件所在的位置。例如,如果我的当前文件夹是 Web\,那么如果我想列出所有 CSS 文件,我将附加类似“Content\CSS”的内容。(我这样做是因为我希望允许用户通过选择要应用的 css 来动态更改站点)。所以它看起来像:
当前路径 += "内容\CSS"
我想将文件名加载到数组或列表中
- 我想将此列表传递给我的视图以在组合框(位于我的 _Layout.cshtml 上)中呈现。
It is important to know that I am trying to view the string on the _Layout.cshtml as I cant just build another view for it. (Unless I am wrong, in that case I would appreicate any help).
重要的是要知道我正在尝试查看 _Layout.cshtml 上的字符串,因为我不能为它构建另一个视图。(除非我错了,在这种情况下,我会感谢任何帮助)。
At the moment I am still working on getting a simple string passed to my view in a way I can freely manipulate it like in step 2.
目前我仍在努力将一个简单的字符串传递给我的视图,我可以像在步骤 2 中那样自由地操纵它。
I started off with a separate static class and a global variable:
我从一个单独的静态类和一个全局变量开始:
public static class MyTheme
{
public static string CurrentPath = HostingEnvironment.MapPath("~");
}
In my view I had: @Html.Label(MyProject.Web.Controllers.MyTheme.CurrentPath);
在我看来,我有:@Html.Label(MyProject.Web.Controllers.MyTheme.CurrentPath);
This worked but when I tried to use an if statement to determine if the string was null or empty I got errors. So my next attempts all failed.
这有效,但是当我尝试使用 if 语句来确定字符串是 null 还是空时,我遇到了错误。所以我接下来的尝试都失败了。
Next I decided to bring it into a controller (in this case my BaseController) and this is when I started running into problems. Code below:
接下来我决定将它带入一个控制器(在本例中是我的 BaseController),这是我开始遇到问题的时候。代码如下:
Inside BaseController Class
内部 BaseController 类
public ActionResult ThemePath()
{
string currentPath = Server.MapPath("~");
if (string.IsNullOrEmpty(currentPath))
{
currentPath = "Error!";
}
else
{
currentPath = "Our Path Is: " + currentPath;
}
return View(currentPath);
}
I dont know how to access and run this from inside my _Layout.cshtml view
我不知道如何从我的 _Layout.cshtml 视图中访问和运行它
So next I tried a standard method inside BaseController:
所以接下来我在 BaseController 中尝试了一个标准方法:
public string ThemePath()
{
string currentPath = Server.MapPath("~");
if (string.IsNullOrEmpty(currentPath))
{
currentPath = "Error!";
}
else
{
currentPath = "Our Path Is: " + currentPath;
}
return currentPath;
}
Again I don't know how to access it in the view
我再次不知道如何在视图中访问它
Finally I tried to use ViewBag and ViewData and now I am just going bonkers! So in my base controller I have:
最后,我尝试使用 ViewBag 和 ViewData,现在我简直要疯了!所以在我的基本控制器中,我有:
public string ThemePath()
{
ViewBag.currentPath = Server.MapPath("~");
if (string.IsNullOrEmpty(ViewBag.currentPath))
{
ViewBag.currentPath = "Error!";
}
else
{
ViewBag.currentPath = "Our Path Is: " + ViewBag.currentPath;
}
return ViewBag.currentPath;
}
and in my view I have
在我看来我有
@Html.Label(ViewBag.CurrentPath);
or even
甚至
@Html.Label(ViewBag.CurrentPath.ToString());
With the following friendly little error messages:
带有以下友好的小错误消息:
CS1973: 'System.Web.Mvc.HtmlHelper' has no applicable method named 'Label' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.
CS1973:“System.Web.Mvc.HtmlHelper”没有名为“Label”的适用方法,但似乎具有该名称的扩展方法。扩展方法不能动态调度。考虑强制转换动态参数或在没有扩展方法语法的情况下调用扩展方法。
Finally I tried ViewData in the base as follows: public string ThemePath() { ViewData["currentPath"] = Server.MapPath("~");
最后,我在基础中尝试了 ViewData,如下所示: public string ThemePath() { ViewData["currentPath"] = Server.MapPath("~");
if (string.IsNullOrEmpty(ViewData["currentPath)"].ToString()))
{
ViewData["currentPath"] = "Error!";
}
else
{
ViewData["currentPath"] = "Our Path Is: " + ViewData["currentPath"];
}
return ViewData["currentPath"].ToString();
}
and correspondingly in the _Layout.cshtml I tried:
并相应地在 _Layout.cshtml 中我尝试过:
@Html.Label(ViewData["CurrentPath"].ToString());
Without the .ToString() I get the above error:
没有 .ToString() 我得到上面的错误:
With the .ToString() I get a null refrence execption error.
使用 .ToString() 我得到一个空引用执行错误。
So I am kinda lost now and don't really know where I am going wrong. Thanks in advance for any help.
所以我现在有点迷茫,真的不知道我哪里出错了。在此先感谢您的帮助。
采纳答案by Steve Hobbs
To pass a string to the view as the Model, you can do:
要将字符串作为模型传递给视图,您可以执行以下操作:
public ActionResult Index()
{
string myString = "This is my string";
return View((object)myString);
}
You must cast it to an object so that MVC doesn't try to load the string as the view name, but instead pass it as the model. You could also write:
您必须将其转换为对象,以便 MVC 不会尝试将字符串加载为视图名称,而是将其作为模型传递。你也可以这样写:
return View("Index", myString);
.. which is a bit more verbose.
..这有点冗长。
Then in your view, just type it as a string:
然后在您的视图中,只需将其键入为字符串:
@model string
<p>Value: @Model</p>
Then you can manipulate Model how you want.
然后你可以按照你想要的方式操作模型。
For accessing it from a Layout page, it might be better to create an HtmlExtension for this:
为了从布局页面访问它,最好为此创建一个 HtmlExtension:
public static string GetThemePath(this HtmlHelper helper)
{
return "/path-to-theme";
}
Then inside your layout page:
然后在您的布局页面中:
<p>Value: @Html.GetThemePath()</p>
Hopefully you can apply this to your own scenario.
希望您可以将其应用到您自己的场景中。
Edit: explicit HtmlHelper code:
编辑:显式 HtmlHelper 代码:
namespace <root app namespace>
{
public static class Helpers
{
public static string GetThemePath(this HtmlHelper helper)
{
return System.Web.Hosting.HostingEnvironment.MapPath("~") + "/path-to-theme";
}
}
}
Then in your view:
那么在你看来:
@{
var path = Html.GetThemePath();
// .. do stuff
}
Or:
<p>Path: @Html.GetThemePath()</p>
或者:
<p>Path: @Html.GetThemePath()</p>
Edit 2:
编辑2:
As discussed, the Helper will work if you add a @usingstatement to the top of your view, with the namespace pointing to the one that your helper is in.
如前所述,如果您@using在视图顶部添加一条语句,并且命名空间指向您的助手所在的名称,则助手将起作用。
回答by Ross
@Steve Hobbs' answer is probably the best, but some of your other solutions couldhave worked. For example,
@Html.Label(ViewBag.CurrentPath);will probably work with an explicit cast, like @Html.Label((string)ViewBag.CurrentPath);. Also, your reference to currentPathin @Html.Label(ViewData["CurrentPath"].ToString());is capitalized, wherein your other code it is not, which is probably why you were getting null reference exceptions.
@Steve Hobbs 的答案可能是最好的,但您的其他一些解决方案可能会奏效。例如,
@Html.Label(ViewBag.CurrentPath);可能会使用显式强制转换,例如@Html.Label((string)ViewBag.CurrentPath);. 此外,您对currentPathin的引用@Html.Label(ViewData["CurrentPath"].ToString());是大写的,其中您的其他代码不是,这可能是您收到空引用异常的原因。
回答by Ventsyslav Raikov
Just define your action method like this
只需像这样定义您的操作方法
public string ThemePath()
and simply return the string itself.
并简单地返回字符串本身。
回答by Saedeas
Why not create a viewmodel with a simple string parameter and then pass that to the view? It has the benefit of being extensible (i.e. you can then add any other things you may want to set in your controller) and it's fairly simple.
为什么不使用简单的字符串参数创建一个视图模型,然后将其传递给视图?它具有可扩展的优点(即,您可以添加任何其他您可能想要在控制器中设置的内容),而且相当简单。
public class MyViewModel
{
public string YourString { get; set; }
}
In the view
在视图中
@model MyViewModel
@Html.Label(model => model.YourString)
In the controller
在控制器中
public ActionResult Index()
{
myViewModel = new MyViewModel();
myViewModel.YourString = "However you are setting this."
return View(myViewModel)
}
回答by Jayant Varshney
Use ViewBag
使用ViewBag
ViewBag.MyString = "some string";
return View();
In your View
在你看来
<h1>@ViewBag.MyString</h1>
I know this does not answer your question (it has already been answered), but the title of your question is very vast and can bring any person on this page who is searching for a query for passing a simple string to View from Controller.
我知道这不能回答你的问题(已经回答了),但是你的问题的标题非常广泛,可以让这个页面上的任何人都在搜索将一个简单的字符串从 Controller 传递给 View 的查询。
回答by live-love
If you are trying to simply return a string to a View, try this:
如果您想简单地将字符串返回给视图,请尝试以下操作:
public string Test()
{
return "test";
}
This will return a view with the word test in it. You can insert some html in the string.
这将返回一个包含单词 test 的视图。您可以在字符串中插入一些 html。
You can also try this:
你也可以试试这个:
public ActionResult Index()
{
return Content("<html><b>test</b></html>");
}

