6

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

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.

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

Thanks

4

1 に答える 1

12

この素晴らしいブログは、デフォルトのモデル バインダーがリストと配列をバインドする方法を理解するのに役立ちます。次のようなページの ViewModel を作成するだけです。

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

次に、「+」jQuery関数で、生成された入力名が次のようなものであることを確認しますlFileModels.[0].Title(またはlFileModels[0].Title、そのリンクをクリックするだけでわかります)

次に、コントローラーでその情報を取得するには、他のフォームと同じです!

[HttpPost]
public ActionResult Index(FileUploadViewModel viewModel)
{

}

編集

MVC ファイルのアップロードに関する別のリンク

編集 2

コードをもう一度読んだ後、検証の問題は、ライブラリが読み込まれた後に目立たない検証を追加したことが原因であることがわかりました。バリデーターを再解析する必要があります。

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

バインディングは、サーバー側の検証と質問の 2 番目の部分に適用されます。

編集 3

フィールドを追加するには、JS で直接行うのではなく、フォームのセクションにファイル フィールドを Ajax でロードする必要があります。追加ボタンをクリックすると、ファイル フィールドの部分ビューが要求され、投稿データに現在のアイテムのリストが表示されます。部分ビューは、追加のフィールドを含むレンダリングされたビューを返します。それは単なるアイデアです。私はそのアイデアを試したことも見たこともありません。私はそれについて考え、共有できると考えました。

于 2012-10-24T13:18:04.080 に答える