Reputation: 51
I am facing a problem, that occurs when I want to redirect the user after the create page, to another page that is not the index page.
I have tried to create another view in the Client folder and then replace "index" by "success" the name of the new page for example.
[HttpPost]
public ActionResult Create(Client client)
{
if (ModelState.IsValid)
{
db.Clients.Add(client);
db.SaveChanges();
return RedirectToAction("Index"); // Here is the problem
}
}
I also try Redirect("~/Client/Success")
but it doesn't work also.
Thank you for your help!
Upvotes: 0
Views: 777
Reputation: 716
You can try a Ajax resquest like that :
$('#myButton').click(function () {
var url = '/MyControllerName/MyPage';
var $Param = $('#SomeParam').val();
$.ajax({
url: url,
type: 'POST',
cache: false,
data: {
Param: $Param
}
})
Upvotes: 0
Reputation: 8850
You need to create not only view named "Success" (actually that isn't required at all), but an action named "Success" in your controller:
[HttpPost]
public ActionResult Create(Client client)
{
if (ModelState.IsValid)
{
db.Clients.Add(client);
db.SaveChanges();
return RedirectToAction("Success");
}
return View(); //Looks like you've missed this line because it shouldn't have compiled if result isn't returned in all code branches.
}
public ActionResult Success(Client client)
{
//...
return View();//By default it will use name of the Action ("Success") as view name. You can specify different View if you need though.
}
But I wouldn't say it's a good idea to use redirect just to show the success result. You better create the Success view in the Client folder as you've done already (assuming your controller is named "ClientController") and then return View result instead of Redirect:
[HttpPost]
public ActionResult Create(Client client)
{
if (ModelState.IsValid)
{
db.Clients.Add(client);
db.SaveChanges();
return View("Success");
}
return View(); //Looks like you've missed this line because it shouldn't have compiled if result isn't returned in all code branches.
}
Upvotes: 2
Reputation: 18873
This will work :
return RedirectToAction("Success","Client");
where Success
is your action name
and Client
is your controller name
if you want to redirect to Success action in same controller then :
return RedirectToAction("Success");
Your action should look like this in ClientController :
public ActionResult Success()
{
return View();
}
You are using :
return RedirectToAction("Index");
this will redirect you to Index
actionresult
in same controller
.
Upvotes: 0
Reputation: 218798
Take a look at the overloads for that method. You're not redirecting to a URL, you're redirecting to an action. So this will redirect to the Index
action on the current controller:
return RedirectToAction("Index");
Or this will redirect to the Success
action on the Client
controller:
return RedirectToAction("Success", "Client");
Upvotes: 0