How do I return two different Views from the same Action in ASP.NET MVC?
I have two views which will both use the same Cont开发者_开发技巧roller method:
//webServiceController.cs
//The actual method is about 40 lines of code. Truncated for readability.
public ActionResult Index()
{
object i = new List<WebServiceMethod>();
i = svcService.populateList("Programs");
return View(i);
}
The first view is an HTML page that displays the data in a pretty table output:
<% // Index.aspx %>
<table>
<tbody>
<% foreach (var item in Model) { %>
<tr>
<td>
<% if (Convert.ToInt32(item.numberRequests) > 0)
{%>
<%= Html.ActionLink("Details", "Details", new { programNumber = item.programNumber })%>
<%} %>
</td>
<td>
<%= Html.Encode(item.programNumber) %>
</td>
</tr>
<% } %>
</tbody>
</table>
The second view is a quick'n'dirty conversion to JSON so that I can do magical AJAX tricks with the data:
<%
// AjaxGetServiceData.aspx
// Convert web service response object into JSON for AJAX.
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
Response.Write(jss.Serialize(Model));
%>
I'd created a duplicate of the Index()
method and called it AjaxGetServiceData()
, but that defeats the purpose of MVC.
Resolution:
I didn't ask my question very well, as evidenced by a 5-10 minute discussion I just had with a coworker about this very topic. He kept asking me the same question that many users on this page asked me: "How does the controller know which view to return?" I responded, "That's what I'm trying to figure out." I was trying to get the method to return a different view (or Json output) when AJAX was the requester. A string argument in the method was my solution.
This is what I ended up using to get my desired effect:
public ActionResult Index(string isJSON = "no")
{
/// ...All the code from before...
if (isJSON == "yes")
{
return Json(i, JsonRequestBehavior.AllowGet);
}
else
{
return View(i);
}
}
Then, when I want the JSON version, in my AJAX request I specify the URL as /MyController/Index/?isJSON=yes
When I want my pretty table view, I just use /MyController/
public ActionResult Index()
{
object i = new List<WebServiceMethod>();
i = svcService.populateList("Programs");
if (someCondition)
return View(i);
else
return View("AjaxGetServiceData", i); // or whatever you called your view.aspx
}
It sounds like you have two different purposes in which case I think you are going the right way when you talk about different controller methods.
Sure, reuse code inside each controller method but if you want a different result, use a different method and keep the controller methods simple.
" ...I was trying to get the method to return a different view (or Json output) when AJAX was the requester..."
public ActionResult Index()
{
object i = new List<WebServiceMethod>();
i = svcService.populateList("Programs");
if (Request.IsAjaxRequest == "True")
{
return Json(i, JsonRequestBehavior.AllowGet);
}
else
{
return View(i)
}
}
精彩评论