Reputation: 12695
I want to pass a string object into a View:
<%@ Page Title="" Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<String>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<h2><%=Model %></h2>
</asp:Content>
When I try this:
return View("SomeView", "stringToPass");
the error occurs: The view 'SomeView' or its master was not found.
but, when I change the return to
return View("SomeView");
everything works fine. So how to pass that string ?
Upvotes: 5
Views: 6871
Reputation: 17354
Old question, but I'll give an example of how to pass string to the View using a model (not using Viewbag which has already been answered)
// Action Method inside controller
public ActionResult Index()
{
string msg = "Hello World";
return View("Index","",msg); // notice the blank second parameter
}
// This goes inside the Index View
// Will print, The Message is: Hello World
The Message is: @Model.ToString()
Upvotes: 0
Reputation: 36037
its confusing it with another overload of View(), do:
return View("SomeView", (object)"stringToPass");
Upvotes: 11
Reputation: 2092
If you're within your "SomeView" action method:
return View("StringToPass");
If you're within a different action method:
return RedirectToAction("SomeView", new { x = "StringToPass" });
EDIT I guess option 1 won't work with a string. I've never tried it b/c I always use ViewModels:
public class UserAdminViewModel
{
public string UserName { get; private set; }
public UserAdminViewModel(string userName)
{
UserName = userName;
}
}
Then you would
return View(new UserAdminViewModel("StringToPass"));
Upvotes: 2
Reputation: 6062
what about
ViewData.Model = "StringToPass";
return View("SomeView");
Upvotes: 3
Reputation: 26882
The View class has a constructor of View("string1", "string2") where string1 is the view's name and string2 is the master page's name. The problem is you're passing in two strings so it's assuming you mean to call that overloaded method.
Upvotes: 2
Reputation: 100567
Use ViewData for this. In your Controller, simply set the key/value pair:
ViewData["Foo"] = "bar";
Then in your View, just access it just as you'd set it previously:
<h2><%=ViewData["Foo"]%></h2>
The problem you were having is that the View()
method's 2 parameters are : View name and Master name.
Upvotes: 4