0

我有以下引导箱片段,我在其中通过 ajax 调用加载消息:

    $.ajax({
        type: "GET",
        url: $("#add-name").val(),
        success: function (data) {
            bootbox.dialog({
                message: data,
                title: "Floorplan Group",
                buttons: {
                    success: {
                        label: "OK",
                        className: "btn-success",
                        callback: function () {
                               //what to do here?
                        }
                    }
                }
            });
        }
    });  

这就是data返回的内容,并加载到我的引导框对话框的正文中。

@model Monitoring.ViewModels.NameViewModel
@using (Html.BeginForm("AddName", "Users", FormMethod.Post, new {@class = "form-horizontal",}))
{    
      @Html.EditorFor(m => m.Name)
}

这是我的控制器:

    [HttpPost]
    public ActionResult AddName(NameViewModel model)
    {
            if (!ModelState.IsValid)
            {
                  //return error
            }
            //add into DB
            return View(model);
    }

如何将表单发布回我的控制器?bootbox 的回调中需要什么代码才能将我的表单发回,如果 ModelState 中有任何错误,我的 bootbox 对话框将保持打开状态,否则对话框将正常关闭。

4

1 回答 1

0

首先在您看来,您需要为您的验证错误消息添加显示,这是让它们全部通过的最简单方法@Html.ValidationSummary(),您也可以考虑使用@Html.ValidationMessageFor(). 我为表单添加了一个 ID,以便更轻松地在 javascript 中发布表单。

@model Monitoring.ViewModels.NameViewModel
@using (Html.BeginForm("AddName", "Users", FormMethod.Post, new {@class = "form-horizontal", @id="SomeFormId"}))
{     @Html.ValidationSummary(false)
      @Html.EditorFor(m => m.Name)
}

我不确定您上面的视图的名称是什么,所以我将其命名为“View1”,在您的控制器中,您需要:

[HttpPost]
public ActionResult AddName(NameViewModel model)
{
    if (!ModelState.IsValid)
    {
         return View("View1", model); // pass the invalid model back to the form view
    }
    //add into DB
    return View(model);
}

在你的 javascript 中:

$.ajax({
    type: "GET",
    url: $("#add-name").val(),
    success: function(data) {
        bootbox.dialog({
            message: data,
            title: "Floorplan Group",
            buttons: {
                success: {
                    label: "OK",
                    className: "btn-success",
                    callback: function() {
                        $("SomeFormId").submit(); // Post the form
                    }
                }
            }
        });
    }
});
于 2014-04-24T12:30:18.390 回答