将简单的字符串从控制器传递到视图MVC3 [英] Pass a simple string from controller to a view MVC3

查看:56
本文介绍了将简单的字符串从控制器传递到视图MVC3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这似乎很基本,应该如此,但是我无法找出我要去哪里. (我在SO上读过其他标题相似的文章,在网络上也读过其他资源,但仍然无法弄清楚),因此将不胜感激.

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.

我有一个控制器,在其中设置了一个字符串变量.现在我不在乎这是采用属性,ActionResult还是直接方法的形式.我只想要一个可以在控制器中使用的简单字符串,然后将其返回到视图.

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.

基本上,我想做的是列出给定文件夹中的文件.所以我的逻辑是这样的:

Essentially what I am trying to do is list the files in a given folder. So my logic is like this:

  1. 查找当前文件夹(部分成功)
  2. 将路径追加到要定位的文件所在的位置.也就是说,如果我当前的文件夹是Web \,那么如果要列出所有CSS文件,则将添加"Content \ CSS"之类的内容. (我这样做是因为我想允许用户通过选择要应用的CSS来动态更改站点).因此,它看起来像:

  1. Find the current folder (partially successful)
  2. 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"

CurrentPath += "Content\CSS"

我想将文件名加载到数组或列表中

I want load the file names into an array or list

重要的是要知道我正在尝试查看_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).

此刻,我仍在努力以一种可以像第2步中那样自由操作它的方式将一个简单的字符串传递给视图.

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.

我从一个单独的静态类和一个全局变量开始:

I started off with a separate static class and a global variable:

public static class MyTheme
{
    public static string CurrentPath = HostingEnvironment.MapPath("~");
}

我认为我有: @ Html.Label(MyProject.Web.Controllers.MyTheme.CurrentPath);

In my view I had: @Html.Label(MyProject.Web.Controllers.MyTheme.CurrentPath);

这可行,但是当我尝试使用if语句确定字符串为null还是为空时,出现错误.所以我的下一次尝试都失败了.

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.

接下来,我决定将其引入控制器(在本例中为BaseController)中,这是我开始遇到问题的时候.下面的代码:

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

    public ActionResult ThemePath()
    {
        string currentPath = Server.MapPath("~");

        if (string.IsNullOrEmpty(currentPath))
        {
            currentPath = "Error!";
        }
        else
        {
            currentPath = "Our Path Is: " + currentPath;
        }

        return View(currentPath);
    }

我不知道如何从_Layout.cshtml视图内部访问和运行它

I dont know how to access and run this from inside my _Layout.cshtml view

因此,接下来我在BaseController中尝试了一种标准方法:

So next I tried a standard method inside 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

最后,我尝试使用ViewBag和ViewData,现在我要疯了!所以在我的基本控制器中,我有:

Finally I tried to use ViewBag and ViewData and now I am just going bonkers! So in my base controller I have:

    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;
    }

在我看来,我有

     @Html.Label(ViewBag.CurrentPath);

甚至

     @Html.Label(ViewBag.CurrentPath.ToString());

出现以下友好的小错误消息:

With the following friendly little error messages:

CS1973:'System.Web.Mvc.HtmlHelper'没有适用的名为'Label'的方法,但似乎具有该名称的扩展方法.扩展方法不能动态调度.考虑强制转换动态参数或在不使用扩展方法语法的情况下调用扩展方法.

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.

最后,我在基础中尝试了ViewData,如下所示: 公共字符串ThemePath() { ViewData ["currentPath"] = Server.MapPath(〜");

Finally I tried ViewData in the base as follows: 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();
    }

并相应地在我尝试过的_Layout.cshtml中:

and correspondingly in the _Layout.cshtml I tried:

     @Html.Label(ViewData["CurrentPath"].ToString());

没有.ToString(),我会收到上述错误:

Without the .ToString() I get the above error:

使用.ToString()时,出现空引用执行错误.

With the .ToString() I get a null refrence execption error.

所以我现在有点迷路了,真的不知道我要去哪里错了.预先感谢您的帮助.

So I am kinda lost now and don't really know where I am going wrong. Thanks in advance for any help.

推荐答案

要将字符串作为模型传递给视图,您可以执行以下操作:

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);
}

您必须将其强制转换为对象,以便MVC不会尝试将字符串作为视图名称加载,而是将其作为模型传递.您还可以写:

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:

return View("Index", myString);

..有点冗长.

然后在您的视图中,只需将其键入为字符串即可:

Then in your view, just type it as a string:

@model string

<p>Value: @Model</p>

然后,您可以根据需要操纵模型.

Then you can manipulate Model how you want.

要从布局"页面访问它,最好为此创建一个HtmlExtension:

For accessing it from a Layout page, it might be better to create an HtmlExtension for this:

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.

显式的HtmlHelper代码:

explicit HtmlHelper code:

namespace <root app namespace>
{
    public static class Helpers
    {
        public static string GetThemePath(this HtmlHelper helper)
        {
            return System.Web.Hosting.HostingEnvironment.MapPath("~") + "/path-to-theme";
        }
    }
}

然后在您看来:

@{
    var path = Html.GetThemePath();
    // .. do stuff
}

或: <p>Path: @Html.GetThemePath()</p>

如前所述,如果在视图顶部添加@using语句,并且命名空间指向您的助手所在的名称,则该助手将起作用.

As discussed, the Helper will work if you add a @using statement to the top of your view, with the namespace pointing to the one that your helper is in.

这篇关于将简单的字符串从控制器传递到视图MVC3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆