繁体   English   中英

从网址动态重定向

[英]Dynamic Redirect from Url.Action

我正在使用通过用户单击按钮时发生的Url.Action传递给Controller的值来构建对象。

$.post("@Url.Action("CreateObj", "ObjectController")", {
    value: $value
})

在调用的方法中,我创建一个对象,为其分配一个ID,然后将该对象保存到数据库中。

public void CreateObj(string value)
{
    Object newObj = Object(value);

    //Magic saving newObj to database

    int id = newObj.objectId; //Saves the object's id to a variable for demo purposes
}

现在,我想立即重定向到该新对象的“编辑”页面,其中URL为“ ./Object/Edit/”+ newObj.objectId。

我尝试在C#CreateObj方法中进行重定向,尝试通过ViewData传递objectId,以便可以在回调函数中进行重定向,但找不到任何一种方法可以正常工作。

如果创建对象之前我不知道ID,并且无法从视图访问它,该如何在创建对象后将用户带到“编辑”页面? 我是否缺少简单的东西?

您可以在创建对象的函数中使用回调,一旦创建了对象,便会触发该回调,将对象ID传递给回调,然后在回调内部将用户重定向到新页面。

假设您的编辑操作方法如下所示

public ActionResult Edit(string value){
   //your magic codes
}

您可以像正常函数调用一样调用它。

public void CreateObj(string value)
{
   Object newObj = Object(value);

   //Magic saving newObj to database

   int id = newObj.objectId; //Saves the object's id to a variable for demo purposes
   Edit(id);   // <-- Normal function call
}

这将自动重定向到编辑页面。

由于您正在执行ajax请求,因此您的Action应该返回所创建对象的ID,并且您应该通过JS处理重定向。 因此,将Action的返回类型和值更改为:

public ActionResult CreateObj(string value) {
    int id = newObj.objectId;
    return Json(id, JsonRequestBehavior.AllowGet);
}

并在您的post()方法上注册一个回调函数以执行重定向:

 $.post("@Url.Action("CreateObj", "Object")", {
                value:"value"
            }).done(function (data) { // data represents the returned id
                //handle success
                window.location.href = `@Url.Action("Edit", "Object")/${data}`;
            }).fail(function () {
                   //Handle failure
            })

•检查$ .post()在jQuery.post()上如何工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM