MVC POST 嵌套格式數(shù)據(jù)到 Controller

我們常常有這樣的需求:控制器Save方法接收一個(gè)復(fù)雜的類(lèi)型,例如:

    public class VisitDetailViewModel
    {
        public WordViewModel Word { get; set; }

        public IEnumerable<PhotoViewModel> Photos { get; set; } 
    }

    public class WordViewModel
    {
        public Guid Id { get; set; }

        [Required]
        [Display(Name = "姓名")]
        [MaxLength(10)]
        public string Name { get; set; }

        [Required]
        [Display(Name = "留言")]
        [MaxLength(100)]
        public string Filepath { get; set; }

        [Display(Name = "時(shí)間")]
        public DateTime CreateTime { get; set; }

        [Display(Name = "置頂")]
        public bool IsTop { get; set; }
    }

    public class PhotoViewModel
    {
        public Guid Id { get; set; }

        public Guid PhotoId { get; set; }

        [Required]
        [MaxLength(100)]
        public string FilePath { get; set; }

        public string AccessFilePath
        {
            get { return MediaService.GetFileAccessUrl(FilePath); }
        }

        [MaxLength(200)]
        public string Description { get; set; }
    }

對(duì)于單個(gè)屬性,前端頁(yè)面表單控件的name屬性為XX.XX,對(duì)于數(shù)組屬性,其控件name屬性設(shè)置為XX[N].XX
代碼如下:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>編輯會(huì)議</title>
    @Styles.Render("~/bundles/global/css")
    @Styles.Render("~/bundles/bootstrap-datetimepicker/css")
    <style type="text/css">
        body { overflow-x: hidden; }
    </style>
</head>
<body>
    <section id="container">
        <div class="panel">
            <div class="panel-body">
                <div class="col-xs-12">
                    <form class="form-horizontal" role="form">
                        @Html.HiddenFor(x => x.Word.Id)
                        @Html.HiddenFor(x => x.Word.Filepath)
                        <div class="form-group">
                            @Html.LabelFor(model => model.Word.Name, new { @class = "control-label col-xs-2" })
                            <div class="col-xs-5">
                                @Html.EditorFor(model => model.Word.Name, new { htmlAttributes = new { @class = "form-control" } })
                                @Html.ValidationMessageFor(model => model.Word.Name, "", new { @class = "text-danger" })
                            </div>
                        </div>

                        <div class="form-group">
                            @Html.LabelFor(model => model.Word.AccessPath, new { @class = "control-label col-xs-2" })
                            <div class="col-xs-10">
                                <img src="@Model.Word.AccessPath" />
                            </div>
                        </div>

                        <div class="form-group">
                            @Html.LabelFor(model => model.Word.CreateTime, new { @class = "control-label col-xs-2" })
                            <div class="col-xs-5">
                                @Html.EditorFor(model => model.Word.CreateTime, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
                                @Html.ValidationMessageFor(model => model.Word.CreateTime, "", new { @class = "text-danger" })
                            </div>
                            @Html.LabelFor(model => model.Word.IsTop, new { @class = "control-label col-xs-2" })
                            <div class="col-xs-3">
                                @Html.CheckBoxFor(x => x.Word.IsTop)
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="control-label col-xs-2">留影</label>
                            <div class="col-xs-10">
                                <div class="col-xs-11">
                                    <table id="table"></table>
                                </div>
                                <div class="col-xs-1">
                                    <button class="btn btn-sm" id="btn-add"><i class="fa fa-plus"></i></button>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-xs-offset-5 col-xs-6">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fa fa-check"></i>
                                    保存
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </section>
</body>
</html>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/global/js")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap-datetimepicker/js")
<script src="~/Scripts/jquery.form.min.js"></script>
<script>
    var updateRowIndex;

    $(function() {
        var i = dialog.getFrameIndex();

        // 提交表單
        $("form").submit(function() {
            // 將table中的數(shù)據(jù)寫(xiě)到form中
            var data = $('#table').bootstrapTable('getData');
            var ok = true;
            $(data).each(function(index, item) {
                if (!item.FilePath || item.FilePath == '') {
                    dialog.alert('請(qǐng)上傳照片,點(diǎn)擊【照片單元格】上傳,點(diǎn)擊【描述單元格】添加描述。', 2);
                    ok = false;
                    return false;
                }
                $('input[name="Photos[' + index + '].Id"]').remove();
                $('input[name="Photos[' + index + '].PhotoId"]').remove();
                $('input[name="Photos[' + index + '].FilePath"]').remove();
                $('input[name="Photos[' + index + '].Description"]').remove();
                $('form').append('<input type="hidden" name="Photos[' + index + '].Id" value="@Model.Word.Id"/>');
                $('form').append('<input type="hidden" name="Photos[' + index + '].PhotoId" value="' + item.PhotoId + '"/>');
                $('form').append('<input type="hidden" name="Photos[' + index + '].FilePath" value="' + item.FilePath + '"/>');
                $('form').append('<input type="hidden" name="Photos[' + index + '].Description" value="' + item.Description + '"/>');
            });
            if (!ok) return false;
            $(this).ajaxSubmit({
                type: "post",
                url: "@Url.Action("Save")",
                beforeSubmit: function (formData, jqForm) {
                    return jqForm.validate().form();
                },
                success: function (responseText, statusText) {
                    if (responseText.errCode == 0) {
                        dialog.msg(responseText.errMsg);
                        top.frames['ifr'].window.Visitor.refresh();
                        dialog.close(i);
                        return;
                    }
                    dialog.alert(responseText.errMsg, 2);
                }
            });
            return false;
        });
    });
</script>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,228評(píng)論 25 708
  • HTML 5 HTML5概述 因特網(wǎng)上的信息是以網(wǎng)頁(yè)的形式展示給用戶(hù)的,因此網(wǎng)頁(yè)是網(wǎng)絡(luò)信息傳遞的載體。網(wǎng)頁(yè)文件是用...
    阿啊阿吖丁閱讀 4,955評(píng)論 0 0
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,659評(píng)論 19 139
  • 2017年5月11日 牛頓力學(xué)與決定論 牛頓提出了力學(xué)三定律之后,整個(gè)人類(lèi)的思想被為其改變。在此之前,人們對(duì)這個(gè)世...
    曉健周閱讀 3,834評(píng)論 2 0
  • 寫(xiě)作是一種輸出的方式。寫(xiě)作也是一種交流方式。參加21天寫(xiě)作社群以來(lái),我每天都在以寫(xiě)作的方式輸出自己。雖然到現(xiàn)在只有...
    簡(jiǎn)邱閱讀 328評(píng)論 0 0

友情鏈接更多精彩內(nèi)容