ASP.NET MVC - How do action names affect the url? - c#

Using MVC out of the box I found the generated URLs can be misleading and I wanted to know if this can be fixed or if my approach/understanding is wrong.
Suppose I have a CreateEgg page, which has a form on it, and once the form is filled in and submitted the user is taken to a ListEggs page with the new egg in it.
So my egg controller will look some thing like this:
public class EggController : Controller
{
public void Add()
{
//do stuff
RenderView("CreateEgg", viewData);
}
public void Create()
{
//do stuff
RenderView("ListEggs", viewData);
}
}
So my first page will have a url of something like http://localhost/egg/add and the form on the page will have an action of:
using (Html.Form<EggController>(c => c.Create())
Meaning the second page will have a url of http://localhost/Egg/Create, to me this is misleading, the action should be called Create, because im creating the egg, but a list view is being displayed so the url of http://localhost/Egg/List would make more scene. How do I achieve this without making my view or action names misleading?

The problem is your action does two things, violating the Single Responsibility Principle.
If your Create action redirects to the List action when it's done creating the item, then this problem disappears.

How A Method Becomes An Action by Phil Haack

ActionVerbs Outlined in Scott Gu's post seem to be a good approch;
Scott says:
You can create overloaded
implementations of action methods, and
use a new [AcceptVerbs] attribute to
have ASP.NET MVC filter how they are
dispatched. For example, below we can
declare two Create action methods -
one that will be called in GET
scenarios, and one that will be called
in POST scenarios
[AcceptVerbs("GET")]
public object Create() {}
[AcceptVerbs("POST")]
public object Create(string productName, Decimal unitPrice) {}

Related

Using httpget when no data is changed?

I remember reading & have been told you should only use [httppost] on controller actions that may change data (I can't find these sources though - and am unable to find anything on Google).
And if you are - say, just doing a lookup of data you should use [httpget].
I have 2 controller actions - used only for looking up data, never for changing it.
I have tried using two [httpget]s this in an ASP.NET MVC 5 controller:
public ActionResult MyAction(Guid Id)
{
// Id is used to populate the form
}
// I would previously have placed [httppost] here
public ActionResult MyAction(MyObject myobj)
{
// myobj is posted back from the form - but no data is changed in the database, it's just a lookup
}
However, I get this error:
The current request for action 'MyAction' on controller type
'MyController' is ambiguous between the following action methods:
The compiler is having a problem with ambiguous method names - so what is best practice for doing this?
Do we have to use a form specifying an explicitly different action? (this seems inelegant and messy - it makes [httppost] look simpler, more elegant and more terse if that is the case).
Is it indeed the case that we should use [httpget] in situations where no data is being persisted?
thx.
Your problem is that you have two methods with the same name in your controller. And action resolver can not decide which one to use.
Easiest way is to follow naming convention, in this case you won't have to put attributes:
public ActionResult GetMyAction(Guid Id)
{
// Id is used to populate the form
}
// I would previously have placed [httppost] here
public ActionResult PostMyAction(MyObject myobj)
{
// myobj is posted back from the form - but no data is changed in the database, it's just a lookup
}
However if you want to stay with your names, you will have to put appropriate attributes:
[HttpGet]
public ActionResult GetMyAction(Guid Id)
{
// Id is used to populate the form
}
// I would previously have placed [httppost] here
[HttpPost]
public ActionResult PostMyAction(MyObject myobj)
{
// myobj is posted back from the form - but no data is changed in the database, it's just a lookup
}
I think you're misunderstanding the rationale for get vs post. The important thing is not that post requests always change the state, the important thing is get requests never change state. One great example was a content management system that regularly experienced their content inexplicably disappearing before figuring out that a web crawler was indexing an admin page and following their deletion hyperlinks, all using http get, or prefetching browsers randomly adding or removing shopping cart items.
That said, I'd probably still make both of these gets using different actions, because the get verb better describes the service action, but maybe you have good reasons not to do that.

In ASP.NET MVC 3, what is filterContext.IsChildAction?

From the sounds of it, it literally is a boolean value of whether or not the action is a child action.
I see this bit of code quite often:
protected override void OnActionExecuting(ActionExecutingContext filterContext) {
if (filterContext.IsChildAction) return;
...
}
It appears to be there to "throttle" unnecessary code execution... but what does filterContext.IsChildAction actually mean?
In view pages, you may often need to inject output of another action into current page - for example, injecting menus. Menu generation may involve lots of business logic (determining rights or users, choosing selected item, etc), so it is not done in the partial view, but in controller.
public class MenuController : Controller
{
[ChildActionOnly]
public ActionResult Menu()
{
MenuViewModel model = GenerateMenu();
return View(model);
}
}
This type of action is called ChildAction, as it cannot(and is not supposed to) be called from outside world(by visiting url). This may only be called by application itself, generally from within the view page.
#Html.Action("Menu", "Menu")
And if you wish(or do not wish) to do some specific stuff when the action being executed is a child action, you inspect filterContext.IsChildAction property.
Maybe it's too late to point out but the accepted answer is slightly misleading, in the sense that:
action marked with ChildActionOnlyAttribute absolutely cannot be run as standalone actions and so it is pointless to test with IsChildAction.
On the other hand if your action is called in two ways
as a regular action
as a child action from within another action
It can be useful to check for IsChildAction so that you can execute additional logic based on the value.

ASP.NET MVC3 - How to serve View() from another controller

So in order accomplish what I asked in this post I did the following:
[iPhone]
[ActionName("Index")]
public ActionResult IndexIPhone()
{
return new Test.Areas.Mobile.Controllers.HomeController().Index();
}
[ActionName("Index")]
public ActionResult Index()
{
return View();
}
Which still serves the same view as the Index action method in this controller. Even though I can see it executing the Test.Areas.Mobile.Controllers.HomeController().Index() action method just fine. What's going on here? And how do I serve the Index view from Mobile area without changing the request URL (as asked in the original post referenced above)?
You have a few options:
Redirect to the Action you'd like to return: return RedirectToAction("Action-I-Want").
Return the View by name: return View("The-View-I-Want").
Note that with the 2nd approach you'd have to put your view in the "Shared" folder for all controllers to be able to find it and return it. This can get messy if you end up putting all your views there.
As a side note: The reason your work doesn't find the view is because default view engine looks for the view in the folder that "belongs" to the current executing controller context, regardless of what code you're calling.
Edit:
It is possible to group all "mobile" views in the same folder. On your Global.asax (or where ever you're setting up your ViewEngine, just add the path to your mobile View in the AreaViewLocationFormats. Mind you, you'll still have to name your views differently.
You can also write your own view engine. I'd do something like detecting the browser and then serving the right file. You could setup a convention like View.aspx, and View.m.aspx.
Anyhow, just take a look at WebFormViewEngine and you'll figure out what works best for you.
The easiest way to send a request to a view handled by another controller is RedirectToAction("View-Name", "Controller-Name").
There are overloads of View() that take route information that might work as well, but they'd require more effort to set up.
Well actually the easiest way is to make one version of your site programmed on standards instead of browser detection :D -- however in direct response to accomplish what it in a more of a ASP.NET mvc fashion, using:
RedirectToAction("ViewName", "ControllerName");
is a good method however I have found it is more practical if you feel you must program for different browser standards to create a primary view and an alternate "mobile" view under your controllers views. Then instead of writing special code on every controller, instead extend the controller like so.
public class ControllerExtended : Controller
{
private bool IsMobile = false;
private void DetectMobileDevices(){ .... }
}
Then modify your controller classes to instead say ControllerExtended classes and just add the one line to the top of each Action that you have alternate views of like so:
public class ApplicationsController : ControllerExtended
{
// GET: /Applications/Index
public ActionResult Index() {
this.DetectMobileDevices();
if(this.IsMobile){
return RedirectToAction("MobileIndex");
} else {
// actual action code goes here
return View();
}
}
}
Alternately you can use return View("ViewName"); but from my experience you want to actually perform different actions as opposed to just showing the result in a different view as in the case of presenting an HTML table as opposed to a Flex table to help iPhone users since there is no flash support in the iPhone, etc. (as of this writing)

asp.net mvc navigation on master page best practices

Trying to create a strongly typed master page with multi level navigation and would love to hear your opinion.
i'm using the sample recommended by MS here:
http://www.asp.net/mvc/tutorials/passing-data-to-view-master-pages-vb
so i have an ApplicationController that gets all the categories and all the other controller inherits it. and it return a LIST and stores it in ViewData["Nav"]
The master page as a partial view that gets the NAV model and creates the menu.
The roues for the category
Category/{CategoryId}/{CategoryName}/{Page}
The question is how can i display the selected category or sub category as selected when i renders it inside the partialView.
I see some options:
1. Create another property in the applicatin controller :
public class CategoryController : AppliactionController
{
//
// GET: /Category/
public ActionResult Index(string categoryId, string categoryName, int page)
{
base.ActiveCategoryId=int.parse(categoryId);
return View();
}
Check the current action URL in the partial view when creating the menu and set the category as selected if it produces the same action URL (not sure if i can get the categoryid from the action)
Any suggestions?
If you're going to use the Master Controller pattern, then option 1 is a suitable solution. For even better separation, you may consider moving that logic in the action into an action filter.
I would avoid option 2 completely, because you don't want that kind of logic in your view.
A third option you can try is to not use the Master Controller pattern, and instead set up your view to call RenderActions on stuff that is orthogonal to the view's main concern. In this case, your view would look something like Html.RenderAction("Menu", Model.CurrentCategoryId)
Regarding your seggestion:
"you may consider moving that logic in the action into an action filter."
I could do that but is it possible to access the controller case controller from the action filter?
should it be something like
public void OnActionExecuting(ActionExecutingContext filterContext)
{
((AppController)filterContext.Controller.base)).ActiveCategoryId=int.parse( filterContext.ActionParameters["CategoryId"])
Didn't check the code, just wanted to hear your thoughts, is this what you suggested?
Thanks

how can i keep my url when my validation fail in asp.net mvc controller action

if i start off on a Detail page:
http:\\www.mysite.com\App\Detail
i have a controller action called Update which normally will call redirectToAction back to the detail page. but i have an error that is caught in validation and i need to return before redirect (to avoid losing all of my ModelState). Here is my controller code:
public override ActionResult Update(Application entity)
{
base.Update(entity);
if (!ModelState.IsValid)
{
return View("Detail", GetAppViewModel(entity.Id));
}
return RedirectToAction("Detail", new { id = entity.Id })
but now I see the view with the validation error messages (as i am using HTML.ValidationSummary() ) but the url looks like this:
http:\\www.mysite.com\App\Update
is there anyway i can avoid the URL from changing without some hack of putting modelstate into some temp variables? Is there a best practice here as the only examples i have seen have been putting ModelState in some tempdata between calling redirectToAction.
As of ASP.NET MVC 2, there isn't any such API call that maintains the URL of the original action method when return View() is called from another action method.
Therefore as such, the recommended solution and a generally accepted convention in ASP.NET MVC is to have a corresponding, similarly named action method that only accepts a HTTP POST verb. So in your case, having another action method named Detail like so should solve your problem of having a different URL when validation fails.
[HttpPost]
public ActionResult Detail(Application entity)
{
base.Update(entity);
if (ModelState.IsValid)
{
//Save the entity here
}
return View("Detail", new { id = entity.Id });
}
This solution is in line with ASP.NET MVC best practices and also avoids having to fiddle around with modestate and tempdate.
In addition, if you haven't explored this option already then client side validation in asp.net mvc might also provide for some solution with regards to your URL problem. I emphasize some since this approach won't work when javascript is disabled on the browser.
So, the best solution would be have an action method named Detail but accepting only HTTP POST verb.
The problem here is actually caused by your implementation. This doesn't answer your question, but it describes where you've gone wrong in the first place.
If you want a page that is used to update or edit an item, the URL should reflect this. For example.
You visit http:\www.mysite.com\App\Detail and it displays some information about something. That is what the URL describes it is going to do. In your controller, the Detail() method would return the Detail.aspx view.
To edit an item, you would visit http:\www.mysite.com\App\Edit and change the information you wish to update, the form would post back to the same URL - you can handle this in the controller with these methods:
[HttpGet]
public ActionResult Edit() {
MyModel model = new MyModel();
...
return View(model);
}
[HttpPost]
public ActionResult Edit(MyModel model) {
...
if (ModelState.IsValid) {
// Save and redirect
...
return RedirectToAction("Detail");
}
return View(model);
}
If you ever find yourself doing this...
return View("SomeView", model);
You are making your own life harder (as well as breaking the principles behind URLs).
If you want to re-use part of a view, make it a partial view and render it inside of the view that is named after the method on the controller.
I apologise that this potentially isn't very helpful, but you are falling into an MVC anti-pattern trap by displaying the same view from a differently named method.
As #Malcolm sais, best practice is to put ModelState in TempData, but don't do it manually! If you'd do this manually in every controller action where it's relevant, you would introduce immense amounts of repeated code, and increase the maintenance cost vastly.
Instead, implement a couple of attributes that do the job for you. Kazi Manzur has an approach (scroll down to the end of the post) that has been widely spread, and Evan Nagle shows an implementation with tests that is essentially the same as Kazi's, but with different names. Since he also provides unit tests that make sure the attributes work, implementing them in your code will mean little or no maintenance cost. The only thing you'll have to keep track of is that the controller actions are decorated with the appropriate attributes, which can also be tested.
When you have the attributes in place, your controller might look something like this (I deliberately simplified, because I don't know the class you inherit from):
[HttpPost, PassState]
public ActionResult Update(EntityType entity)
{
// Only update if the model is valid
if (ModelState.IsValid) {
base.Update(entity);
}
// Always redirect to Detail view.
// Any errors will be passed along automagically, thanks to the attribute.
return RedirectToAction("Detail", new { id = entity.Id });
}
[HttpGet, GetState]
public ActionResult Detail(int id)
{
// Get stuff from the database and show the view
// The model state, if there is any, will be imported by the attribute.
}
You mention that you feel putting ModelState in TempData feels like a "hack" - why? I agree with you that doing it with repeated code in every single controller action seems hacky, but that's not what we're doing here. In fact, this is exactly what TempData is for. And I don't think the above code looks hacky... do you?
Although there are solutions to this problem that might appear simpler, such as just renaming the action method to preserve the URL, I would strongly advise against that approach. It does solve this problem, but introduces a couple of others - for example, you'll still have no protection against double form submission, and you'll have pretty confusing action names (where a call to Detail actually changes stuff on the server).
The best practice you ask for is actually what you explained not to do: putting modelstate into tempdata. Tempdata is meant for it, that's why I would not call it a hack.
If this is to much repetitive code you could use the attribute modeldatatotempdata of MVCContrib. But the store is still TempData.

Categories