ASP .Net核心模型绑定到集合

时间:2016-09-20 07:52:58

标签: asp.net-core model-binding

我是ASP .Net Core 1.0的新手,我试图将视图绑定到包含同一对象集合的模型。主要模型是问卷,可能包含任何不同类型的问题。但我的问题在于ActionResult方法,我的List属性在post期间始终为null。

这是表格:

<form id="mainForm" asp-controller="Default" asp-action="PersonalDetails" asp-route-sectionTypeCode="@Model.SectionTypeCode" asp-route-sectionNumber="@Model.SectionNumber" method="post" asp-anti-forgery="false">
        @{
            for (Int32 i = 0; i < Model.Questions.Count; i++)
            {
                string spacerValue = "";
                if (i == Model.Questions.Count - 1)
                {
                    spacerValue = "extraLargeSpacerBottom";
                }
                <div class="form-group @spacerValue">
                    <label>@Model.Questions[i].QuestionTitle</label>
                    @{
                        switch (Model.Questions[i].QuestionTypeCode)
                        {
                            case 1:
                                <input asp-for="Questions[i].Value" class="form-control appInput" type="text">
                                break;

                            case 2:
                                <input asp-for="Questions[i].Value" class="form-control appInput" type="number">
                                break;

                            case 3:
                                <select asp-for="Questions[i].Value" class="form-control appInput" asp-items="Model.Questions[i].QuestionOptions"></select>
                                break;

                            case 4:
                                <input asp-for="Questions[i].Value" class="form-control appInput" type="date">
                                break;

                            case 5:
                                <div>
                                    <label class="radio-inline">
                                        <input asp-for="Questions[i].Value" value="true" type="radio"><span class="radioSpace">Yes</span>
                                    </label>
                                    <label class="radio-inline">
                                        <input asp-for="Questions[i].Value" value="false" type="radio"><span class="radioSpace">No</span>
                                    </label>
                                </div>
                                break;

                            case 6:
                                <input asp-for="Questions[i].Value" class="form-control appInput" type="number">
                                break;
                        }
                    }
                </div>
            }
        }
    </form>

这是_Question类:

public class _Question
{
    #region Properties
    public string QuestionTitle { get; private set; }
    public string QuestionHelp { get; private set; }
    public Int32 QuestionTypeCode { get; private set; }
    public string ValidationMessage { get; private set; }
    public List<SelectListItem> QuestionOptions { get; private set; }

    public dynamic Value { get; set; }
    #endregion

    public _Question() { }

    public _Question(Int32 questionTypeCode, string questionTitle, string questionHelp, List<SelectListItem> options = null)
    {
        QuestionTypeCode = questionTypeCode;
        QuestionTitle = questionTitle;
        QuestionHelp = questionHelp;
        QuestionOptions = options;

        switch (questionTypeCode)
        {
            case 1:
                ValidationMessage = "Please enter a text value";
                break;

            case 2:
                ValidationMessage = "Please enter a numeric value";
                break;

            case 4:
                ValidationMessage = "Please enter a date value";
                break;

            case 6:
                ValidationMessage = "Please enter a currency value";
                break;
        }
    }
}

主模型包含一个在运行时从数据库生成的_Question对象列表。

有人可以帮我解决一下我的空结果吗?

2 个答案:

答案 0 :(得分:1)

您的控制器是如何设置的?根据我对模型绑定所做的操作,控制器需要设置一定的方式以与模型(或视图模型)重合以接受后期数据。基本上,您希望确保模型中的所有内容与帖子数据完全一致。

例如:

查看型号:

public class ExampleCustomerViewModel
{
    public string[] CustomerTypes { get; set; }
    public bool Address { get; set; }
    public bool City { get; set; }
    public bool County { get; set; }
    public bool ProvinceState { get; set; }
    public bool Country { get; set; }
    public bool PostalZip { get; set; }
}

然后是控制器:

    [HttpPost]
    public IActionResult ExampleAction(ExampleCustomerViewModel viewModel)
    {
        if (!ModelState.IsValid)
            return BadRequest();

        viewModel.DoWhatever();

        return PartialView("~/Sites/ExampleCustomer.cshtml", viewModel);
    }

然后我使用了一些jQuery:

     function performCustomerInitialization() {

    //Dummy code where I am get the values I want from the form into JSON. 
                formParameters = {
                    CustomerTypes: customerTypes,
                    Address: $("#Address").prop("checked") === true,
                    City: $("#City").prop("checked") === true,
                    County: $("#County").prop("checked") === true,
                    ProvinceState: $("#ProvinceState").prop("checked") === true,
                    Country: $("#Country").prop("checked") === true,
                    PostalZip: $("#PostalZip").prop("checked") === true

                };

            $.ajax({
                url: "ExampleAction",
                type: "POST",
                async: true,
                data: formParameters,
                dataType: "html",
                success: function (results) {
                    $(resultsDiv).empty().append(results);
                    console.log(formParameters);
                },
                error: function () {
                    $(resultsDiv).empty().append("<div class='box-body'><br/><p><em>An error occurred.</em></p><br/></div></div>");
                }
            });
        }

希望这有助于指明你正确的方向!

答案 1 :(得分:1)

模型绑定不适用于私有集。 Setter必须是公共的,以便MVC可以在回发中设置值

public class _Question
{
    #region Properties
    public string QuestionTitle { get; private set; }
    public string QuestionHelp { get; private set; }
    public Int32 QuestionTypeCode { get; private set; }
    public string ValidationMessage { get; private set; }
    public List<SelectListItem> QuestionOptions { get; private set; }
    //...
}

您可以找到有关模型绑定here

的更多详细信息