I have a following types of url used in my Application.
localhost/admin/userdetail/id
localhost/admin/userdetail/id/true
localhost/admin/userdetail/id/true/success
Here is my Admin Controller
bool inSaveAction, string status are optional
[Authorize]
public ActionResult UserDetail(string Id, bool inSaveAction, string status)
{
}
[HttpPost, Authorize, ValidateAntiForgeryToken]
public ActionResult SaveUserDetail(UserDetailViewModel viewModel)
{
User userToSave = new User();
AdminService.UpdateUser(userToSave);
//This is calling the above function as it sending all 3 params
return RedirectToAction("UserDetail", new { Id = viewModel.Id,
inSaveAction = true, status = "success" });
}
Below case is not working
@Html.ActionLink("DisplayName", "UserDetail", new { id = Model.Id })
In Global.asax
routes.MapRoute("UserDetail",
"UserDetail/{id}",
new
{
controller = "Admin",
action = "UserDetail",
id = UrlParameter.Optional
}
);
I followed http://haacked.com/archive/2011/02/20/routing-regression-with-two-consecutive-optional-url-parameters.aspx
How can i make inSaveAction & status as optional parameter for my UserDetail action?
You're missing the parameters in your route config. In order to make this work with different parameters optional (as in Phil Haack's post), you need to define multiple routes
routes.MapRoute("UserDetail-WithStatus",
"UserDetail/{id}/{inSaveAction}/{status}",
new
{
controller = "Admin",
action = "UserDetail",
// nothing optional
}
);
routes.MapRoute("UserDetail-WithoutStatus",
"UserDetail/{id}/{inSaveAction}",
new
{
controller = "Admin",
action = "UserDetail",
// nothing optional
}
);
routes.MapRoute("UserDetail-WithoutSaveAction",
"UserDetail/{id}",
new
{
controller = "Admin",
action = "UserDetail",
id = UrlParameter.Optional
}
);
And then create links with:
@Html.ActionLink("Link", "Index", "Admin", new { id = 1, inSaveAction = true, success = "success" }, null)
You'll also need to set the optional parameters as nullable, otherwise you'll get exceptions if id or inSaveAction are missing.
public ActionResult UserDetail(int? id, bool? inSaveAction, string status)
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With