问题
I am just playing with ASP.NET MVC 2 for learning. I can pass my models to view but after spend 1-2 hour i am unsuccessful to pass data to view.For example:
www.example.com/home/show/asdf i am trying to get asdf string for show it on screen.
public ActionResult Test(string ID)
{
return View(ID);
}
With this method i am trying to capture it.Then return view. In my view, i use <%: Html.LabelFor(m=>m as string) %> . This can be looking stupidly. I think that all strings on urls mapping to methods but not integers so i think i have to use question mark like this example.com/home/Test?asdf ? i will try this too.
Edit:
Passing integer on url to method argument get confused me. Example.com/home/test/2 in this url,2 will be argument of test method so i thought same thing for string. I think we can only pass integer and not possible to do samething with any other values.So i think i can only catch values by querystring so still how can i pass a simple string type to view ?
回答1:
You cannot call View function like that. Actually you can but it will look for a View named whatever you type in URL. It won't use your Test View. You cannot pass a string as a model because it has to be an object. Check View method overloads. I suggest you create a class for model, then send it to the View.
I suggest something like this.
public ActionResult Test(string id)
{
SomeModelClass model=new SomeModelClass(id);
return View(model);
}
If you want to pass a string, you should cast it as an object like this
public ActionResult Test(string id)
{
return View((Object)id);
}
回答2:
public ActionResult Test(string ID)
{
ViewData["ID"] = ID
return View();
}
<p>
<div class="simple">
<%= Html.Encode(ViewData["ID"]) %>
</div>
回答3:
Try
public ActionResult Test(string ID)
{
return View("Test", ID);
}
来源:https://stackoverflow.com/questions/3178887/i-cant-pass-a-value-to-view