asp.net-mvc - 在 MVC 4 中的另一个表单中验证 JQuery UI 模式表单

标签 asp.net-mvc jquery-ui asp.net-mvc-4 jquery-ui-dialog form-submit

我在 MVC 4 中有一个表单,其中包含多个字段,并且根据组合的值,我需要打开一个模式对话框表单并加载到这 3 个附加字段中,这些字段将影响我的同一实体我在主窗体中创建/编辑。 对于这个模式对话框,我使用的是 jQuery UI 中的对话框。

现在,我需要做的是验证(必需)模式对话框中的字段,以便允许用户保留输入的值,这些值稍后将由主表单提交。

我的问题是如何在模态表单中执行这 3 个字段的验证(因为在对话框关闭之前它们无法提交主表单)。

有什么提示或想法吗?

问候, 塞萨尔。

最佳答案

您可以使用 AJAX 将表单模式提交到服务器。模态表单当然会有一个与之关联的单独的 View 模型。我们来举例说明:

主视图模型:

public class MyViewModel
{
    [DisplayName("select a value")]
    public string SelectedValue { get; set; }
    public IEnumerable<SelectListItem> Values { get; set; }
    public string SomeOtherProperty { get; set; }
}

模态对话框 View 模型:

public class DialogViewModel
{
    [Required]
    public string Prop1 { get; set; }
    [Required]
    public string Prop2 { get; set; }
    [Required]
    public string Prop3 { get; set; }
}

然后你可以有一个包含 4 个操作的 Controller :

public class HomeController : Controller
{
    // Renders the main form
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            Values = new[]
            {
                new SelectListItem { Value = "1", Text = "item 1" },
                new SelectListItem { Value = "2", Text = "item 2" },
                new SelectListItem { Value = "3", Text = "item 3" },
            }
        };
        return View(model);
    }

    // Processes the submission of the main form
    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return Content(
            string.Format(
                "Thanks for filling out the form. You selected value: \"{0}\" and other property: \"{1}\"",
                model.SelectedValue,
                model.SomeOtherProperty
            )
        );
    }

    // Renders the partial view which will be shown in a modal
    public ActionResult Modal(string selectedValue)
    {
        var model = new DialogViewModel
        {
            Prop1 = selectedValue
        };
        return PartialView(model);
    }

    // Processes the submission of the modal
    [HttpPost]
    public ActionResult Modal(DialogViewModel model)
    {
        if (ModelState.IsValid)
        {
            // validation of the modal view model succeeded =>
            // we return a JSON result containing some precalculated value
            return Json(new
            {
                value = string.Format("{0} - {1} - {2}", model.Prop1, model.Prop2, model.Prop3)
            });
        }

        // Validation failed => we need to redisplay the modal form
        // and give the user the possibility to fix his errors
        return PartialView(model);
    }
}

接下来你可以有一个主视图(~/Views/Home/Index.cshtml):

@model MyViewModel

@using (Html.BeginForm())
{
    <div>
        @Html.LabelFor(x => x.SelectedValue)
        @Html.DropDownListFor(x => x.SelectedValue, Model.Values, new { id = "ddl" })
    </div>
    <div>
        @Html.LabelFor(x => x.SomeOtherProperty)
        @Html.TextBoxFor(x => x.SomeOtherProperty, new { id = "otherProperty" })
        @Html.ActionLink(
            "click here to open a modal and help you fill the value",
            "Modal",
            "Home",
            null,
            new { id = "showModal" }
        )
    </div>
    <button type="submit">OK</button>
}

<div id="modal"></div>

以及包含模态表单的部分 View (~/Views/Home/Modal.cshtml):

@model DialogViewModel

@using (Ajax.BeginForm(new AjaxOptions { OnSuccess = "handleModalSubmit" }))
{
    <div>
        @Html.LabelFor(x => x.Prop1)
        @Html.EditorFor(x => x.Prop1)
        @Html.ValidationMessageFor(x => x.Prop1)
    </div>
    <div>
        @Html.LabelFor(x => x.Prop2)
        @Html.EditorFor(x => x.Prop2)
        @Html.ValidationMessageFor(x => x.Prop2)
    </div>
    <div>
        @Html.LabelFor(x => x.Prop3)
        @Html.EditorFor(x => x.Prop3)
        @Html.ValidationMessageFor(x => x.Prop3)
    </div>
    <button type="submit">OK</button>
}

好的,现在剩下的就是编写一些 JavaScript 来让整个事情变得生动起来。我们首先确保已包含所有必需的脚本:

<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.20.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

然后编写我们自己的:

$(function () {
    $('#showModal').click(function () {
        $.ajax({
            url: this.href,
            type: 'GET',
            cache: false,
            data: { selectedValue: $('#ddl').val() },
            success: function (result) {
                $('#modal').html(result).dialog('open');
            }
        });
        return false;
    });

    $('#modal').dialog({
        autoOpen: false,
        modal: true
    });
});

function handleModalSubmit(result) {
    if (result.value) {
        // JSON returned => validation succeeded => 
        // close the modal and update some property on the main form
        $('#modal').dialog('close');
        $('#otherProperty').val(result.value);
    } else {
        // validation failed => refresh the modal to display the errors
        $('#modal').html(result);
    }
}

关于asp.net-mvc - 在 MVC 4 中的另一个表单中验证 JQuery UI 模式表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13868980/

相关文章:

asp.net - 何时使用 BindAttribute?

asp.net-mvc - ASP.NET MVC - 局部 View 可以有 Controller 吗?

javascript - 每次我在棋盘上拖放棋子时都会出现错误

javascript - 从 onClick() 加载完整 View

c# - 带有 MVC 4 的 VS 2010 中关于缺少对 Microsoft.CSharp.dll 和 System.Core.dll 的引用的警告消息

c# - 一个站点可多次登录或多个站点

asp.net-mvc - MVC3 在迷你分析器调用 Find : Index step? 期间到底在做什么

javascript - 无法在加载的模态中触发点击事件

javascript - jQuery UI 位置设置 "right"和 "bottom"而不是 "left"和 "top"

jquery-ui - JQuery UI 对话框只能水平调整大小,不能垂直调整