Asp.Net Mvc Multiple Attribute Routing - asp.net-mvc

I have a controller (CarsController).
I want to set multiple route to action in this controller. For example;
public class CarsController : Controller
{
[Route("cars/create")]
[Route("cars/edit/{id}")]
public action CreateOrEdit(int? id)
{
...
}
}
But I can not. What's the problem?

Following code is great work. Thank You Tetsuya Yamamoto..
[Route("cars/{type:regex(create|edit)}/{id?}")]
public async Task<ActionResult> CreateOrEdit(long? id)
{
await FillViewBag();
if (id.HasValue)
{
return View(await this.Database.Cars.Include(i => i.Files).SingleAsync(id.Value));
}
return View();
}
When using in action
#Url.Action("CreateOrEdit", new { type="create"})

Related

How To call An Action In Umbraco Controller?

I created an Umbraco DocumentType with the alias Personal and created a controller that inherits
Umbraco.Web.Mvc.RenderMvcController
I added two Actions, one is the default action and the other is called Test.
How can I fire the Test Action from the Personal controller?
public class PersonalController : Umbraco.Web.Mvc.RenderMvcController
{
// GET: Personal
public override ActionResult Index(RenderModel model)
{
return base.Index(model);
}
public String Test(RenderModel model)
{
return "fff";
}
}
When I put the url like this: localHost/personal/test it shows:
No umbraco document matches the url '/test'.
Which is right, so how can I call it?
I would do it like this
[HttpPost]
public ActionResult SubmitSearchForm(SearchViewModel model)
{
if (ModelState.IsValid)
{
if (!string.IsNullOrEmpty(model.SearchTerm))
{
model.SearchTerm = model.SearchTerm;
model.SearchGroups = GetSearchGroups(model);
model.SearchResults = _searchHelper.GetSearchResults(model, Request.Form.AllKeys);
}
return RenderSearchResults(model.SearchResults);
}
return null;
}
public ActionResult RenderSearchResults(SearchResultsModel model)
{
return PartialView(PartialViewPath("_SearchResults"), model);
}
See this blog post for the full context behind where this code snippet came from.
http://www.codeshare.co.uk/blog/how-to-search-by-document-type-and-property-in-umbraco/

ASP.NET MVC - Routing Structure

I have an ASP.NET MVC 4.5 app. In this app, I have two controllers: Parent and Children. The look something like this:
[RoutePrefix("dashboard/parents")]
public partial class ParentsController : Controller
{
public ActionResult Index()
{
return View();
}
[Route("add")]
public ActionResult Add()
{
return View();
}
}
[RoutePrefix("dashboard/children")]
public partial class ChildrenController : Controller
{
public ActionResult Index()
{
return View();
}
[Route("add")]
public ActionResult Add()
{
return View();
}
}
At this time, these controllers work how I want. However, in my ChildrenController, I want to add something like an overload to the add route. In other words, I'd like for the user to be able to visit: /dashboard/parents/{parentId}/children/add. This URL would be used to add a child to a specific parent. My question is, how do I update my controllers to allow for this type of scenario?
thank you!
I think what you are looking for the is "~" to override your default routeprefix.. The following example is taken from the asp.net website which tells you how to accomplish the task.
[RoutePrefix("api/books")]
public class BooksController : ApiController
{
// GET /api/authors/1/books
[Route("~/api/authors/{authorId:int}/books")]
public IEnumerable<Book> GetByAuthor(int authorId) { ... }
// ...
}

mvc controller default action

Say I have a controller with multiple actions, is there an override to make the controller return a default action if a condition is met?
Example:
I have a checkoutcontroller and I want each action to return HttpNotFound() if e-commerce is disabled on the site, is there a better way of doing it than just doing the following:
public class CheckoutController
{
[HttpGet]
public ActionResult ViewBasket()
{
if (AppSettings.EcommerceEnabled)
{
return View();
}
else
{
return HttpNotFound();
}
}
[HttpGet]
public ActionResult DeliveryAddress()
{
if (AppSettings.EcommerceEnabled)
{
return View();
}
else
{
return HttpNotFound();
}
}
}
You can create a custom action filter that will be used for action methods inside CheckoutController.
public class CommercePermissionAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (AppSettings.EcommerceEnabled)
{
base.OnActionExecuting(filterContext);
}
else
{
// Example for redirection
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "Controller", "Error" },
{ "Action", "AccessDenied" }
});
}
}
}
Then you can use this filter on each action method by
[HttpGet]
[CommercePermission]
public ActionResult ViewBasket()
Or if you want whole controller actions to have this filter,
[CommercePermission]
public class CheckoutController
You can even apply filters globally to all actions in your project.
You can find more info here.
You could create a custom action filter. This would intercept the routing to that action, apply its internal logic, and either continue to the action or interrupt it as you define in the filter. Filters can be applied to individual actions, an entire controller class, or even globally for the whole application.

Redirect to same view

I am working on a ASP.NET MVC website and I am new to this.
I have a controller with few actions. I want to use these actions through out my website.
For example
[HttpPost]
public ActionResult MyAction(ViewModel model)
{
if (ModelState.IsValid)
{
//code is here
}
return RedirectToAction(); // redirect to same view
}
I want to redirect to same view from where request is generated. I am not sure if this is possible or not ?
Based on your comment, I would create a Controller that looks like:
public MyController : Controller
{
private ActionResult SharedMethod(SomeModel model)
{
if (ModelState.IsValid)
{
//code is here
}
// viewname is required, otherwise the view name used will be
// the original calling method (ie public1.cshtml, public2.cshtml)
return this.View("SharedViewName");
}
public ActionResult Public1(SomeModel model)
{
return this.SharedMethod(model);
}
public ActionResult Public1(SomeModel model)
{
return this.SharedMethod(model);
}
}

C# ASP.NET MVC: Find out whether GET or POST was invoked on controller action

How do I find out whether a GET or a POST hit my ASP.NET MVC controller action?
You can check Request.HttpMethod for that.
if (Request.HttpMethod == "POST") {
//the controller was hit with POST
}
else {
//etc.
}
You can separate your controller methods:
[AcceptVerbs(HttpVerbs.Get)]
public ViewResult Operation()
{
// insert here the GET logic
return SomeView(...)
}
[AcceptVerbs(HttpVerbs.Post)]
public ViewResult Operation(SomeModel model)
{
// insert here the POST logic
return SomeView(...);
}
You can also use the ActionResults For Get and Post methods separately as below:
[HttpGet]
public ActionResult Operation()
{
return View(...)
}
[HttpPost]
public ActionResult Operation(SomeModel model)
{
return View(...);
}

Resources