Pass a simple string from controller to a view MVC3

前端 未结 6 1706
青春惊慌失措
青春惊慌失措 2021-01-31 02:19

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 we

6条回答
  •  一向
    一向 (楼主)
    2021-01-31 02:46

    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:

    return View("Index", myString);
    

    .. which is a bit more verbose.

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

    @model string
    
    

    Value: @Model

    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:

    public static string GetThemePath(this HtmlHelper helper)
    {
        return "/path-to-theme";
    }
    

    Then inside your layout page:

    Value: @Html.GetThemePath()

    Hopefully you can apply this to your own scenario.

    Edit: explicit HtmlHelper code:

    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:

    Path: @Html.GetThemePath()

    Edit 2:

    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.

提交回复
热议问题