为什么我的表单没有被发布到正确的控制器动作?

时间:2011-07-19 05:42:07

标签: jquery asp.net-mvc-3

如何在区域注册中区分这两条路线?

这是该地区注册的最后两条路线。

第一条路线是加载视图的时间。工作正常。

第一个路线加载一个表格,然后发布到同一个控制器但行动不同。

我从来没有从控制器那里得到好的。由于路由问题,它可能不会命中控制器。

我缺少什么?

    context.MapRoute(
        "Load",
        "app/respond/{Id}",
        new { controller = "Controller1", action = "Index" }
    );

    context.MapRoute(
        "Update",
        "app/respond/{action}",
        new { controller = "Controller1", action = "Update" }
    );

这是表单的外观:

@using (Html.BeginForm("Update", "Respond", FormMethod.Post, new { id = "frmUpdate" }))
{
   //all form fields go here
}

这是发布的方式:

$('#frmUpdate').submit(function () {
    //verify all field values

    $.ajax({
        url: this.action,
        type: this.method,
        data: $(this).serialize(),
        success: function (result) {
            if (result.s == 'OK')
                alert("Success! Response updated");
            else
                alert("Sorry! Update failed.");//this is what I get
        }
    });

    return false;
});

我的控制器:

[HttpPost]
public ActionResult Update(MyModel model)
{
    return Json(new { s = "OK", m = "Hi from controller" });
}

1 个答案:

答案 0 :(得分:1)

您无法区分这两条路线,因为它们遵循完全相同的网址格式app/respond/something。您没有对something施加任何约束,因此第一条路线将始终匹配。

如果您希望路由系统能够区分您需要使用约束,例如假设{id}必须只包含数字:

context.MapRoute(
    "Load",
    "app/respond/{id}",
    new { controller = "Controller1", action = "Index" },
    new { id = @"[0-9]+" }
);

context.MapRoute(
    "Update",
    "app/respond/{action}",
    new { controller = "Controller1", action = "Update" }
);

现在,当您请求app/respond/123时,将调用Index操作,当您调用app/respond/FooBar时,将调用FooBar操作。如果您请求app/respond,则会调用Update操作。