MVC模型验证一个动态的形式? [英] MVC Model Validation on a dynamic form?

查看:167
本文介绍了MVC模型验证一个动态的形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号:

I have the following Model :

public class FileModel
{
    public int Id { get; set; }

    [Required(ErrorMessage = "Required")]
    [StringLength(100, ErrorMessage = "Max is 100, Min is 3", MinimumLength = 3)]
    public string Name { get; set; }

    public string Path { get; set; }

    [Required(ErrorMessage = "Required")]
    public string FileTypeId { get; set; }

    public DateTime RegistrationDate { get; set; }
}

以下是我的看法:

the following is my view :

@using (Html.BeginForm("Index", "FileManagement", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <table class="content-table" style="min-width: 600px; border-spacing: 15px;">
        <tr>
            <td colspan="4" class="table-header">New File
                <div class="add-icon">+</div>
            </td>
        </tr>
        <tr>
            <td>Name: </td>
            <td>@Html.TextBoxFor(q => q.NewFile.Name, new { maxlength = "100", id = "NewFile_Name1", name = "NewFile.Name1" })
                <br />@Html.ValidationMessageFor(q => q.NewFile.Name)
            </td>
            <td>
                <input type="file" id="FileUploadField1" /></td>
            <td style="width: 16px; text-align: center;">&nbsp;</td>
        </tr>
        <tr>
            <td colspan="4" style="text-align: center;">
                <input type="submit" value="Submit" />
            </td>
        </tr>
    </table>
    <script type="text/javascript">

        $('.content-table .add-icon').click(function () {
            var lastFileField = $('.content-table input[type="file"]').last();
            var lastId = lastFileField.attr('id').replace(/\D*/g, '');
            lastId = parseInt(lastId) + 1;
            var newFields = '<tr>' +
                '<td>Name : </td>' +
                '<td><input data-val="true" data-val-length="Max chars is 100, Min chars is 3" data-val-length-max="100" data-val-length-min="3" data-val-required="Required" id="NewFile_Name' + lastId + '" name="NewFile.Name' + lastId + '" type="text" value="" /><br /><span class="field-validation-valid" data-valmsg-for="NewFile.Name' + lastId + '" data-valmsg-replace="true"></span></td>' +
                '<td><input type="file" id="FileUploadField' + lastId + '"/></td>' +
                '<td style="text-align:right;"><div class="delete-icon"></div></td>' +
                '</tr>';
            var lastTr = $(lastFileField).parents('tr:first')[0];
            $(lastTr).after(newFields);
        });

        $('.content-table .delete-icon').live('click', function () {
            $(this).parents('tr:first').remove();
        });
    </script>
}

正如你所看到的,我们必须上传一个或多个文件的形式。所以,我增加了一个+按钮的用户,他们可以添加一个文件域形成。


用户必须输入该文件的名称,并选择要上传的文件。但MVC客户端验证只是验证与剃须刀添加的第一个输入。


我怎么能强迫MVC验证在客户端和服务器端验证所有领域。

As you can see, We have a form for uploading one or more files. So, I've added an + button for users that they can add a file field to form.

Users must enter the name of the file and select a file for uploading. But MVC client validator just validate the first inputs that added with Razor.

How can I force MVC validator to validate all fields at the client side and server side.

的另一个问题是:

我们如何处理在MVC控制器获取字段值。

Another question is:
How can we handle getting the field values at a MVC Controller.

感谢

推荐答案

这个伟大的博客将帮助您了解默认的模型绑定如何绑定列表和数组。只要为您的网页一个ViewModel看起来有点像这样的:

This great blog will help you understand how the default model binder will bind lists and arrays. Just make a ViewModel for your page that looks somewhat like this:

public class FileUploadViewModel
{
    public List<FileModel> lFileModels { get; set; }
}

然后在你的+jQuery函数,确保产生的输入名称类似 lFileModels。[0] .title伪(或者它可能是 lFileModels [0] .title伪,只需点击该链接,你就看着办吧)

Then in your "+" jQuery function, make sure the generated input names are something like lFileModels.[0].Title (or it might be lFileModels[0].Title, just click that link and you'll figure it out)

然后获得在控制器的信息,它就像任何其他形式的!

Then to get that info in the controller, it's just like any other form!

[HttpPost]
public ActionResult Index(FileUploadViewModel viewModel)
{

}

修改

的MVC文件上传另一个链接

编辑2

再次阅读您的code一次后,我现在意识到,验证问题是由于该库被加载后,加入不显眼的验证。你必须重新解析验证。

After reading your code once again, I now realise that the validation problem is due to adding unobtrusive validations after the library was loaded. You have to re-parse the validators.

$("form").data("validator", null);
$.validator.unobtrusive.parse($("form"));

的结合适用于服务器端验证和你问题的第二部分。

The binding applies to server-side validation and the 2nd part of your question.

修改3

有关添加字段,而不是做直JS,你应该阿贾克斯加载表格与文件字段的部分。当您单击Add按钮,它要求与文件中的字段的局部视图,在它的后数据显示,目前的项目清单。局部视图然后返回一个额外的领域的渲染视图。这只是一个想法。我没有尝试过,甚至看到这一想法。我只是,虽然它和我能够分享。

For adding fields, instead of doing it straight in JS, you should Ajax load the section of your form with the file fields. When you click on the add button, it request a partial view of the file fields with, in it's post data, a list of the current items. The partial view then returns a rendered view with an extra field. It's just an idea. I haven't tried or even seen that idea. I just though about it and figured I could share it.

这篇关于MVC模型验证一个动态的形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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