为什么我的MVC 3 Form没有被发布到正确的控制器动作?

时间:2011-07-10 09:12:33

标签: asp.net-mvc-3

我有一个通过Index()动作渲染得很好的视图。 基本上我从DB读取并加载到我的模型中。

当用户填写或更改值并点击提交时,我希望将表单发布到同一控制器上的其他操作。

但是表单会被提交到默认的index()动作。

最终目标是让用户保持在同一页面上,但显示提交结果。

以下是我的代码:

注册路线的区域注册:

context.MapRoute(
                "Test",
                "app/test/{Id}",
                new { controller = "Test", action = "Index" }
            );

控制器:

[HttpGet]
public ActionResult Index(string rk, string g){
  TestModel model = new TestModel();
  //Now read from DB & populate the model
  return View(model);  
}

这是我要提交的帖子:

[HttpPost]
public ActionResult Update(TestModel model)
{
    model = new TestModel();
    model.Status = "Form Posted!";

    return View("Index", model);
}

以下是我的观点:

@using (Html.BeginForm("Update", "Test", FormMethod.Post, new { id="frmUpdate"}))
{
   //My form fields get populated by model
   <button type="submit" id="btnUpdate" onclick="return ValidateAndSubmit(this.id, 'result_label');">Update</button>
}

JS拦截器提交点击:

function ValidateAndSubmit(b, l) {
        //do validation before submit
        if (AnyFieldNotValid) { alert('failed'); return false; }
        else {
            $("#frmUpdate").submit();
        }        
    }

我做错了什么?

修改 我不能做一个$ .ajax()的帖子,因为我在表格上有一个recaptcha。

2 个答案:

答案 0 :(得分:1)

您的路由不允许使用操作参数,因此发布到该控制器的任何内容都将路由到您提供的默认操作,即Index。请尝试以下方法:

context.MapRoute(
    "Test",
    "app/test/{action}",
    new { controller = "Test", action = "Index" }
);

这会将/app/test路由到Index操作,/app/test/update路由到Update操作。

答案 1 :(得分:0)

可能是这样的2条路线来解决404:

        context.MapRoute(
            "Test1",
            "app/test/{Id}",
            new { controller = "Test", action = "Index" }
        );

        context.MapRoute(
            "Test2",
            "app/test/{action}",
            new { controller = "Test", action = "Update" }
        );
相关问题