[英]Redirection to a another page asp.net mvc
我遇到一个问题,当我想在创建页面后将用户重定向到不是索引页面的另一个页面时,会发生此问题。
我尝试在Client文件夹中创建另一个视图,然后将“ index”替换为“成功”新页面的名称。
[HttpPost]
public ActionResult Create(Client client)
{
if (ModelState.IsValid)
{
db.Clients.Add(client);
db.SaveChanges();
return RedirectToAction("Index"); // Here is the problem
}
}
我也尝试了Redirect("~/Client/Success")
但是它也不起作用。
谢谢您的帮助!
您不仅需要创建名为“ Success”的视图(实际上根本不需要),还需要在控制器中创建一个名为“ Success”的操作 :
[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.
}
但是我不会说仅使用重定向来显示成功结果是一个好主意 。 您最好像已经完成的那样在Client文件夹中创建Success视图(假设您的控制器名为“ ClientController”),然后返回View结果而不是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.
}
这将起作用:
return RedirectToAction("Success","Client");
其中Success
是您的action name
, Client
是您的controller name
如果要重定向到同一控制器中的“成功”操作,则:
return RedirectToAction("Success");
您的操作在ClientController中应如下所示:
public ActionResult Success()
{
return View();
}
您正在使用 :
return RedirectToAction("Index");
这会将您重定向到同一controller
Index
actionresult
。
看一下该方法的重载 。 您没有重定向到URL ,而是重定向到操作 。 因此,这将重定向到当前控制器上的Index
操作:
return RedirectToAction("Index");
或这将重定向到Client
控制器上的Success
操作:
return RedirectToAction("Success", "Client");
您可以尝试这样的Ajax请求:
$('#myButton').click(function () {
var url = '/MyControllerName/MyPage';
var $Param = $('#SomeParam').val();
$.ajax({
url: url,
type: 'POST',
cache: false,
data: {
Param: $Param
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.