Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC have An Action render another Action

Tags:

asp.net-mvc

I have two pages I need, and want to show for the url /index and /review. The only difference between the two pages is on the review I will have a review comment section to show and Submit button. Otherwise the two pages are identical. I thought I could create a user control for the main content.

However, if I could say under the Review action, flag to show review stuff and them return the rest of the index action.

How would you (generic you) do this?

like image 840
Chance Robertson Avatar asked Dec 31 '22 03:12

Chance Robertson


2 Answers

Model example

public class MyModel
{
  public bool ShowCommentsSection { get; set; }
}

Controller actions

public ActionResult Index()
{
  var myModel = new MyModel();

  //Note: ShowCommentsSection (and the bool type) is false by default.

  return View(myModel);
}

public ActionResult Review()
{
  var myModel = new MyModel
  {
    ShowCommentsSection = true
  };

  //Note that we are telling the view engine to return the Index view
  return View("Index", myModel);
}

View (somewhere inside your index.aspx probably)

<% if(Model.ShowCommentsSection) { %>
  <% Html.RenderPartial("Reviews/ReviewPartial", Model); %>
<% } %>

Or, if Razor is your cup of tea:

@if(Model.ShowCommentsSection) {
  Html.RenderPartial("Reviews/ReviewPartial", Model);
}
like image 169
Dan Atkinson Avatar answered Jan 28 '23 03:01

Dan Atkinson


// ... Make comment section visible
return Index();
like image 45
Spencer Ruport Avatar answered Jan 28 '23 03:01

Spencer Ruport