Is there a way to extend the RedirectToAction method on mvc 5 for accepts masterName parameter. I'm looking for something like this:
RedirectToAction(actionName: "Index", controllerName: controllerName, masterName: "_Layout");
Can you guys help me?
You can pass route values.
return RedirectToAction(actionName: "Index", controllerName: controllerName, new {masterName = "_Layout"});
The action method should have a parameter with name masterName. This parameter will then receive the value given here. You can then inside the controller action pass on the parameter to the view.
public ActionResult Index(string masterName)
{
// Other code
return View("Index", masterName);
}
Related
I want to use an actionlink to call a controller. My URL is
localhost:16252/Concert/Index/9.
I want to call create controller and send id (9) to the controller. How to access the id (9) from address bar by actionlink?
ActionLink has one overload that allows you to specify routevalues
MSDN Link here
#Html.ActionLink("LinkText", "Action", "Controller", new {Id= 9}, null)
For Passing from View you have to use overload which takes parameter of RouteValueDictionary:
#Html.ActionLink("Link Text","MyAction", "My", new {id= 9},null)
and in your controller:
public class MyController
{
public ActionResult MyAction(int id)
{
// do something
return View();
}
}
Using this overload of Html.ActionLink()
I want to send a parameter to a view from an action that resolves and sends that value. The issue is that when the parameter "arrives" to the view, it arrives null giving me an error when I try to manage it.
The code I have in the action is (it creates the parameter and send it):
public ActionResult CreateAccount(Account model)
{
try
{
if (ModelState.IsValid)
{
_repository = new Repository();
model.PublicadorId = GetPublicadorId();
model.CreatedDate = DateTime.Now;
model.ModifiedDate = DateTime.Now;
model.IsActive = true;
Int32 id = _repository.Store(model);
return RedirectToAction("SubirImagenes/" + id, "Account");
}
}catch{}
}
So, the action that manage the parameter sent is (note that I pass the parameter as a nullable to avoid errors, and the name of the parameter is the same as the name I use to call the RedirectToAction before):
[HttpPost]
[AuthorizeUser]
[ValidateAntiForgeryToken]
public ActionResult UploadImage(CompraVenta.Models.UploadFileModel fileModel, Int32? id)
{
string directory = #"C:\Folder\";
if (ModelState.IsValid)
{
if (fileModel != null && fileModel.File != null && fileModel.File.ContentLength > 0)
{
var fileName = Path.GetFileName(fileModel.File.FileName);
fileModel.File.SaveAs(Path.Combine(directory, fileName));
}
return RedirectToAction("Index");
}
return View();
}
[AuthorizeUser]
public ActionResult SubirImagenes()
{
return View();
}
Any help would be appreciated. The routing roules of my application is:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
You are using it wrong way, you have to pass parameter using this overload of RedirectToAction() which takes object of RouteValueDictionary as parameter.
Do like this:
return RedirectToAction("UploadImage", "Account", new {id = id});
UPDATE:
you cannot pass parameters the way told above if action is HttpPost, the workaround is to directly call action without using RedirectToAction like:
return UploadImage(null,id);
Call the method directly instead of using RedirectToAction like:
return UploadImage(null,id);
instead of
return RedirectToAction("UploadImage/" + id, "Account");
Note:- address in the browser would be of old method
You can add an anonymous object to the RedirectToAction for the action parameters:
return RedirectToAction("Index", "Home", new {id = id});
Finally I've found the solution. In the "get" action "SubirImagenes" I get the parameter and then, with a strong typed model, using a hidden field, I pass the parameter in the "post" action receiving it inside the model I pass as a parameter in that post action.
My existing MVC code contains an action routine something like this:
[HttpPost]
public ActionResult Register1(SomeViewModel model)
{
return RedirectToAction("Register", new { p = model.PageNumber - 1 });
}
I want to move this code to a library routine:
public static ActionResult ProcessPost(Controller controller, string action,
int pageNumber)
{
// Redirect to the specified action on the specified controller
return new RedirectToRouteResult( <something here> );
}
and call it from the action routine like this:
return ProcessPost(this, "register", model.PageNumber);
Can some kind person give me the <something here> code that yields an ActionResult that redirects to the specified action (specified by the string argument) on the specified Controller (specified by the Controller argument?
Taking a look at the documentation on RedirectToRouteResult seems pretty straight forward:
var routeValues = new RouteValueDictionary();
routeValues.Add("Action", action);
routeValues.Add("Controller", controller.GetType().Name);
routeValues.Add("PageNumber", pageNumber);
var result = new (RedirectToRouteResult(routeValues);
After some experimentation, this appears to be a simple solution:
return new RedirectResult(controller.Url.RouteUrl(
new { action = action, p = pageNumber }
));
Apparently, the Url method on a specific Controller instance is smart enough to use that instance to get the controller name part of the full URL.
I want to have links http://localhost:2409/Account/Confirmation/16 and that link http://localhost:2409/Account/Confirmation/ (without parametr). But with this action methods, it isn't working. Why?
public ActionResult Confirmation(int id, string hash)
{
Some code..
return View();
}
second, I just want to return View, if parametr is empty.
public ActionResult Confirmation()
{
return View();
}
Error (translated):
The current request for action on a controller Confirmation
AccountController is ambiguous between the following methods of
action: System.Web.Mvc.ActionResult Confirmation (Int32,
System.String) for type TC.Controllers.AccountController
System.Web.Mvc.ActionResult Confirmation () for type
TC.Controllers.AccountController
You cannot have multiple actions with the same name using the same HTTP verb (in your case GET.) You can name your actions differently but this means the link will change or you can use different VERB but this can also leads to other problems like you cannot just enter the link in your browser.
What you should do is to change your id to be optional with int? and merge your two actions into one:
public ActionResult Confirmation(int? id, string hash)
{
if(id.HasValue)
{
//Some code.. using id.Value
return View();
}
//There was no Id given
return View();
}
You may also need to allow in your route that the id is optional. If you are using the default routes this should be the default setting:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
There is no need to make 2-methods for it. Your HTTP request get confused that which ActionMethod should be called on both cases;
http://localhost:2409/Account/Confirmation/16
http://localhost:2409/Account/Confirmation/
Instead of all this, just create a single method. Make its parameter optional or assign some default value to the parameters. Here are 2-examples to understand it.
// 1. Default value to paramter
public ActionResult Confirmation(int id = 0, string hash = null)
{
//Some code..
return View();
}
// 2. Make id optional
public ActionResult Confirmation(int? id, string hash)
{
//Some code..
return View();
}
You can adopt any one approach from them.
Is it possible to overload the action methods based on number of parameters in request?
Eg:
1.
domain.com/List/Filter/ByName
invokes -> public ActionResult Filter(string criteria1)
2.
domain.com/List/Filter/ByName/ByRanking
invokes -> public ActionResult Filter(string criteria1, string criteria2)
I'm using asp.net mvc2.
Action methods cannot be overloaded based on parameters because there would be no reasonable way to disambiguate a URL into multiple overloaded methods.
What you can do, though is either this:
public ActionResult Filter(string criteria1, string criteria2)
and then check whether criteria2 is null to filter only by name.
Alternatively, you can use ActionNameAttribute to decorate your action methods
[ActionName("FilterByName")]
public ActionResult Filter(string criteria1)
[ActionName("FilterByNameAndRanking")]
public ActionResult Filter(string criteria1, string criteria2)
and then use that name in route registration. This approach, however, can lead to much confusion.
If I'm not mistaken the best way to do this would be to add two different controller methods and map them to two different Urls.
public ActionResult Filter1(string criteria1);
public ActionResult Filter2(string criteria1, criteria2);
Then you have two route definitions:
This will map this URL List/Filter/xxCriteria/ to the first controller
routes.MapRoute(
"Filter", // Route name
"{controller}/Filter/{criteria1}", // URL with parameters
new { controller = "List", action = "Filter1", criteria="" } // Parameter defaults
);
This will map this URL List/Filter/xxCriteriaName/xxxCriteriaRank to the second controller. Without this route you could still map a url to the second method, but it would look like : List/Filter/?criteria1=xx&criteria2=xx
routes.MapRoute(
"Filter2", // Route name
"{controller}/Filter/{criteria1}/{criteria2}", // URL with parameters
new { controller = "List", action = "Filter2", criteria1 = "", criteria2 = "" } // Parameter defaults
);
Hope it helped.