我使用Ajax
调用在创建视图中创建记录,在创建记录后,我将id
和title
值返回到success
Ajax
方法。我通过向其发送id和title值,在成功中调用另一个名为已完成的视图。但是,我无法在Url.Action
方法中使用success
,因为我无法在其中获取响应值。另一方面,当我使用下面提到的另一种方式时,我不想在参数中使用&
或?
。那么,我该如何解决这个问题?
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = null)])
{
//some stuff
var redirectUrl = new UrlHelper(Request.RequestContext).Action("Completed", "Issue", new { /* no params */ });
return Json(new { success= true, url = redirectUrl, id= model.ID, title = model.Title, });
}
public ActionResult Completed()
{
return View(new { id = Request.Params[0].ToString(), title = Request.Params[1].ToString() });
}
查看(创建):
$('form').submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: '@Url.Action("Create", "Issue")',
data: formdata,
dataType: "json",
success: function (response) {
if (response.success) {
//Method I : Cannot use response values at here
window.location.href = '@Url.Action("Completed", "Issue", new { id = response.id, title = response.title })';
//Method II : I do not want to use ? as it is not recommended for security
window.location.href = response.url + "?id=" response.id.toString() + "&title=" + response.title;
}
}
});
});
查看(已完成):
<div>
@(ViewContext.RouteData.Values["id"]) - @(ViewContext.RouteData.Values["title"]) has been created.
</div>
答案 0 :(得分:1)
根据您的路线配置方式,您可以执行以下操作:
window.location.href = response.url + "/id/" response.id.toString() + "/title/" + response.title;
最终结果如下:http://www.example.com/id/19/title/theTitle
但是我会非常小心,因为有人可以很容易地模仿那个电话并访问你的行动方法。
答案 1 :(得分:0)
在Url.Action中使用任何唯一硬编码值作为id和title,然后将其替换为响应值。见下文,例如 - :
$('form').submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: '@Url.Action("Create", "Issue")',
data: formdata,
dataType: "json",
success: function (response) {
if (response.success) {
window.location.href = @Url.Action("Completed", "Issue", new { id = "newid", title ="newtitle" }).replace('newid',response.id).replace('newtitle',response.title);
}
}
});
});