Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET MVC Explicit Views

Tags:

c#

asp.net-mvc

Hey, one more newbie here, just playing around with .NET MVC. My main task is to have a few semi-static pages on URLs like:

  • /about/
  • /about/contacts/
  • /about/jobs/

I'm using a controller for that called Static and have the following route attached:

routes.MapRoute(
  "About",
  "about/{id}",
  new { controller = "Static", action = "Index", id = UrlParameter.Optional }
);

It seems to work fine as I have the Static controller with the Index method which uses a switch statement to identify which page has to be viewed. I use the RedirectToAction() function to call other actions of the Static controller in order to display pages with other views. My views are:

  • /Static/About.aspx
  • /Static/Contacts.aspx
  • /Static/Jobs.aspx

This method seems to work fine, but what I don't like about it is the redirect, so browsing to /about/contacts I get a redirect to /Static/Contacts which is not what I'd really like to see in the URL.

So my question is - what is the correct way of doing this? And is there a way to explicitly call a certain view from my Index action?

Thanks, ~ K.

like image 583
kovshenin Avatar asked Mar 18 '26 21:03

kovshenin


2 Answers

Don't do the redirect. Instead of using a switch statement within the Index action, have a separate action for each page (ie. About, Contacts, Job) each with their own view.

Your Static controller could look something like this:

public ActionResult Index()
{
    return View();
}

public ActionResult About()
{
    return View();
}

public ActionResult Contacts()
{
    return View();
}

public ActionResult Jobs()
{
    return View();
}

And if you needed to do any processing specific to Contacts or Jobs, it can be done within their respective actions.

To explicitly call a certain view:

return View("ViewName");

There are seven overloads for the View() method. A number of which allow you to pass the Model:

return View("ViewName", Model);
like image 145
Rohrbs Avatar answered Mar 20 '26 12:03

Rohrbs


I'd recommend moving away from Static, and have an About controller. Within that controller, one method per page.

public ActionResult About() 
{
   return View ("About");
}

//Jobs() and Contacts() follow the same pattern

3 routes to match:

routes.MapRoute(
  "Jobs",
  "about/jobs",
  new { controller = "About", action = "Jobs" }
);

routes.MapRoute(
  "Contact",
  "about/contact",
  new { controller = "About", action = "Contact"  }
);

routes.MapRoute(
  "About",
  "about/",
  new { controller = "About", action = "About" }
);
like image 36
p.campbell Avatar answered Mar 20 '26 12:03

p.campbell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!