从网址动态重定向

时间:2018-10-12 16:39:50

标签: javascript c# asp.net-mvc asp.net-core

我正在使用通过用户单击按钮时发生的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,并且无法从视图中访问它,如何在创建对象后将用户带到“编辑”页面?我想念一些简单的东西吗?

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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
}

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

答案 2 :(得分:0)

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

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()上工作。

相关问题