如何发布包含集合的模型?

时间:2016-03-28 18:55:48

标签: c# jquery asp.net-mvc razor asp.net-core-mvc

拥有一个包含空列表的模型。我想在列表中添加项目并一次性发布。

主要模式

[Required]
public string WillAttend { get; set; }

/// <summary>
/// Guests to accompany the RSVPer
/// </summary>
public List<Guest> Guests { get; set; }

来宾模型

[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }

[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }

表格内:

<div class="form-group">
    <div>
        Yes @Html.RadioButtonFor(m => m.WillAttend, "yes", new { @class = "" })
        No @Html.RadioButtonFor(m => m.WillAttend, "no", new { @class = "" })
    </div>
</div>
<div class="form-group">
    <div>
        <span>Will you bringing any children or guests?</span>
        <input id="InputAddGuest" type="button" class="form-control" value="Add Guest or Child" />                            
        <ul id="ListGuest">

        </ul>
    </div>
</div>

<div class="form-group">
    <div>
        <button type="submit" class="btn btn-block">Finish</button>
    </div>
</div>

页面上有一个表单用于提交上面的主模型,我使用jquery生成html:

<script type="text/javascript">

    $(document).ready(function () {
        $('#InputAddGuest').click(function () {
            $('#ListGuest').append('<li>HELLO WORLD</li>');
        });
    });

</script>

但是这里有什么,以便当我发布我的模型时包含实际的客人?

2 个答案:

答案 0 :(得分:1)

您基本上需要使用与视图模型属性层次结构匹配的输入字段名来构建html标记。

由于您的主视图模型具有一个集合的Guests属性,因此您的输入字段的名称应该类似于Guests[0].FirstNam e,Guests[0].LastNameGuests[1].FirstName等。

这应该有效

$(document).ready(function () {
    $('#InputAddGuest').click(function () {
       var index = $(".guestRow").length;
       var row = "<div class='guestRow'>";
       row += "<input type='text' name='Guests[" + index + "].FirstName' />";
       row += "<input type='text' name='Guests[" + index + "].LastName' />";
       row += "</div>";
       $('#ListGuest').append(row);
    });
});

假设您的HttpPost操作方法参数是MainModel类型

[HttpPost]
public ActionResult Register(MainModel model)
{
    //check model.WillAttend
    // iterate through model.Guests
    // to do : return something
}

答案 1 :(得分:0)

List

我有类似的情况,在Feature。

我所做的是:我在控制器上进行会话,所以当

$('#InputAddGuest').click(function () {

        });

我这样叫$ .ajax:

  var valDdlTeamProject = $('#TeamProjectCollection').val();
        var valDdlProject = $('#Project').val();
$.ajax({
                type: 'POST',
                dataType: 'json',
                url: '@Url.Action("AddTfsFeature", "Request")',
                data: {
                    requestNo: '@Model.RequestNo',
                    teamProjectCollection: valDdlTeamProject,
                    project: valDdlProject
                },
                success: function (response) {
                    if (response.Result == 'Success') {
                        var additionalHtml = "";
                        var additionalHtml = '<a class="label label-info" href="#">';
                        additionalHtml += response.TempObject.TeamProjectCollection + ' - ' + response.TempObject.Project;
                        additionalHtml += '<span class="glyphicon glyphicon-remove remove-feature" data-ID="' + response.TempObject.ID + '" onclick="removeFeature(\'' + response.TempObject.ID + '\', this)"></span>';
                        additionalHtml += '</a>';
                        $('.body-add-feature').append(additionalHtml);
                        clearTfsFeatureForm();
                        iCounterFeature = response.TempObjectCount;
                        if (response.TempObjectCount > 0)
                            $('#DialogCreateFeature').modal('hide');
                    }
                    if (response.Result == 'Failed') {
                        alert(response.Message);
                    }
                },
                error: function (response) { }
            })

代码背后:

[HttpPost]
        public JsonResult AddTfsFeature(string requestNo, string teamProjectCollection, string project)
        {
            ResultMessageViewModel result = new ResultMessageViewModel
            {
                Result = "Failed",
                Message = "No data"
            };

            TfsFeature feature = new TfsFeature
            {
                ID = sessTempIndexTfsFeature,
                RequestNo = requestNo,
                TeamProjectCollection = teamProjectCollection,
                Project = project,
                CreatedBy = UserID
            };
            for (int i = 0; i < sessListTfsFeature.Count; i++)
            {
                if (sessListTfsFeature.ElementAt(i).TeamProjectCollection == teamProjectCollection &&
                    sessListTfsFeature.ElementAt(i).Project == project)
                {
                    result.Result = "Failed";
                    result.Message = "Existing feature data has already exist.";
                    return Json(result, JsonRequestBehavior.AllowGet);
                }
            }
            sessListTfsFeature.Add(feature);

        result.Result = "Success";
        result.Message = "Add Success";
        result.TempObject = feature;
        result.TempObjectCount = sessListTfsFeature.Count;
        return Json(result, JsonRequestBehavior.AllowGet);

sessListTfsFeature是List<TfsFeature>

如果有删除Guest的按钮,则需要新的ajax和新的控制器来删除会话中的对象Guest。