How to create a controller action called 'event' - asp.net-mvc

I need to add an action to my controller called 'event', but that's a reserved word. What's the easiest way to add an event action?
Eg:
public class entertainmentController : Controller
{
// GET: entertainment
public ActionResult Index()
{
return View();
}
// GET: entertainment/event
public ActionResult event() // <-- won't compile
{
return View();
}
}

Use the ActionName attribute
// GET: entertainment/event
[ActionName("event")]
public ActionResult EntertainmentEvent()
{
return View("EntertainmentEvent");
}

While I'd recommend against it, this will compile:
public ActionResult #event()
{
return View();
}

you can do that in route mapping. just add a route entertainment/event in RouteConfig and map that route to a custom action..lets say 'randomAction'

Related

Add 2 ActionResult DeleteConfirmed in 1 controller

Is it possible to have 2 ActionResult DeleteConfirmed in 1 controller?
I have 2 different views that I want to delete.
Thanks,
EB
[HttpPost, ActionName("DeleteLink")]
public ActionResult DeleteConfirmed(int id)
{
Link link = db.Links.Find(id);
db.Links.Remove(link);
db.SaveChanges();
return RedirectToAction("OutOfBank");
}
It seems that you want to overload DeleteConfirmed action. You can use the attribute if you want your code to do overloading.
[ActionName("MyOverloadedName")]
But, you'll have to use a different action name for the same http method.
So it's just semantics at that point. Would you rather have the name in your code or your attribute?
Code Example:
public class HomeController : Controller
{
public ActionResult GetEmpName()
{
return Content("This is the test Message");
}
[ActionName("GetEmpWithCode")]
public ActionResult GetEmpName(string EmpCode)
{
return Content("This is the test Messagewith Overloaded");
}
}
Phil has an article related to this: http://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx

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 Multiple Attribute Routing

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"})

asp.net mvc controller with multiple lists and "return to list" link

If you have 5 list views in a controller and in each list you can go to edit, details or delete.
On the edit, details and delete page youo have a link 'return to list'.
What's the best method to 'remember' to which list action you must return?
As a solution I've put some info like CurrentAction in the ViewModel and used that in the View. But if you want to use this with different controllers instead of one...
(You can use a Currentcontroller, CurrentArea, but that's not a 'beautifull' solution)
public class MyController : Controller
{
public ActionResult Index()
{
...
}
public ActionResult List2()
{
...
}
public ActionResult List3()
{
...
}
public ActionResult List4()
{
...
}
public ActionResult Create(...)
{
...
}
[HttpPost]
public ActionResult Create(...)
{
...
}
public ActionResult Edit(...)
{
...
}
[HttpPost]
public ActionResult Edit(...)
{
...
}
public ActionResult Delete(...)
{
...
}
[HttpPost]
public ActionResult Delete(...)
{
...
}
}
thanks
Filip
You can use Request.UrlReferrer Property to examine from where did user come to delete ot edit screens.Then bind url to return to list command.
You can set TempData["ReturnUrl"] in your caller action and then use it to set the url of return to list hyperlink.

Routing to the actions with same names but different parameters

I have this set of routes:
routes.MapRoute(
"IssueType",
"issue/{type}",
new { controller = "Issue", action = "Index" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Here is the controller class:
public class IssueController : Controller
{
public ActionResult Index()
{
// todo: redirect to concrete type
return View();
}
public ActionResult Index(string type)
{
return View();
}
}
why, when i request http://host/issue i get The current request for action 'Index' on controller type 'IssueController' is ambiguous between the following action methods:
I expect that first one method should act when there is no parameters, and second one when some parameter specified.
where did i made mistake?
UPD: possible duplicate: Can you overload controller methods in ASP.NET MVC?
UPD 2: due to the link above - there is no any legal way to make action overloading, is it?
UPD 3: Action methods cannot be overloaded based on parameters (c) http://msdn.microsoft.com/en-us/library/system.web.mvc.controller%28VS.100%29.aspx
I would have one Index method that looks for a valid type variable
public class IssueController : Controller
{
public ActionResult Index(string type)
{
if(string.isNullOrEmpty(type)){
return View("viewWithOutType");}
else{
return View("viewWithType");}
}
}
EDIT:
How about creating a custom attribute that looks for a specific request value as in this post StackOverflow
[RequireRequestValue("someInt")]
public ActionResult MyMethod(int someInt) { /* ... */ }
[RequireRequestValue("someString")]
public ActionResult MyMethod(string someString) { /* ... */ }
public class RequireRequestValueAttribute : ActionMethodSelectorAttribute {
public RequireRequestValueAttribute(string valueName) {
ValueName = valueName;
}
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) {
return (controllerContext.HttpContext.Request[ValueName] != null);
}
public string ValueName { get; private set; }
}
I ran into a similar situation where I wanted my "Index" action to handle the rendering if I had an ID specified or not. The solution I came upon was to make the ID parameter to the Index method optional.
For example, I originally tried having both:
public ViewResult Index()
{
//...
}
// AND
public ViewResult Index(int entryId)
{
//...
}
and I just combined them and changed it to:
public ViewResult Index(int entryId = 0)
{
//...
}
You can do it using an ActionFilterAttribute that checks the parameters using reflection (I tried it) but it's a bad idea. Each distinct action should have its own name.
Why not just call your two methods "Index" and "Single", say, and live with the limitation on naming?
Unlike methods that are bound at compile time based on matching signatures, a missing route value at the end is treated like a null.
If you want the [hack] ActionFilterAttribute that matches parameters let me know and I'll post a link to it, but like I said, it's a bad idea.
All you have to do is mark your second Action with [HttpPost]. For instance:
public class IssueController : Controller
{
public ActionResult Index()
{
// todo: redirect to concrete type
return View();
}
[HttpPost]
public ActionResult Index(string type)
{
return View();
}
}

Resources