验证另一种形式的内JQuery用户界面模式窗体在MVC 4 [英] Validate JQuery UI modal form within another form in MVC 4

查看:115
本文介绍了验证另一种形式的内JQuery用户界面模式窗体在MVC 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MVC 4一种形式,其中包含几个字段,并根据组合的价值,我需要打开一个模式对话框的形式,并加载到一个另外3个领域,将针对我同一个实体影响米创建/编辑的主要形式。
对于这种模态对话框我使用的jQuery UI的一个。

I have a form in MVC 4 which contains several fields and, depending on the value of a combo, I need to open a modal dialog form and load into that one 3 additional fields that will impact against the same entity that I'm creating/editing in the main form. For this modal dialog I'm using the one from jQuery UI.

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

Now, what I need to do is to validate (Required) the fields within the modal dialog in order to allow the user to retain the entered values which will be submited later by the main form.

我的问题是如何从模式窗体中执行的3场的验证(因为他们直到关闭对话框不将能够提交的主要形式)。

My problem is how to perform the validation of those 3 fields from within the modal form (because they wouldn't be able to submit the main form until dialog is closed).

任何提示或想法?

问候,
塞萨尔。

Regards, Cesar.

推荐答案

您可以使用AJAX的形式模式提交给服务器。模态形式将有当然与它关联的单独视图模型。让我们来举例说明:

You could use AJAX to submit the form modal to the server. The modal form will have of course a separate view model associated with it. Let's exemplify:

主视图模型:

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

模态对话框视图模型:

Modal dialog view model:

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

然后,你可以有一个包含4动作控制器:

Then you could have a controller containing 4 actions:

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);
    }
}

接下来你可以有一个主视图(〜/查看/主页/ 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>

和遏制模态形式的局部视图(〜/查看/主页/ Modal.cshtml

and a partial view to contain the modal form (~/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来使整个事情还活着。首先,我们要确保我们已经包括了所有所需的脚本第一:

OK, now all that's left is write some javascript to make the whole thing alive. We start by making sure that we have included all the required scripts first:

<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>

,然后写我们自己的:

and then write our own:

$(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);
    }
}

这篇关于验证另一种形式的内JQuery用户界面模式窗体在MVC 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆