自定义模型绑定器返回具有正确结构的空对象

时间:2016-11-05 10:52:56

标签: asp.net-mvc custom-model-binder

我尝试使用自定义绑定器创建模型对象:

public class AccidentProtocolStep4ModelBinder : DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext,
        Type modelType)
    {
        var request = controllerContext.HttpContext.Request;
        var witnessesFromRequest = new List<Person>();
        var i = 0;
        while (request.Form.AllKeys.Any(x => x.StartsWith(string.Format("Witnesses[{0}]", i))))
        {
            witnessesFromRequest.Add(new Person
            {
                FirstName = request.Form.Get(string.Format("Witnesses[{0}][FirstName]", i)),
                LastName = request.Form.Get(string.Format("Witnesses[{0}][LastName]", i)),
                MiddleName = request.Form.Get(string.Format("Witnesses[{0}][MiddleName]", i)),
            });
            i++;
        }

        return new AccidentProtocolStep4Model
        {
            Witnesses = witnessesFromRequest
        };
    }
}

我已将此Binder添加到Global.asax:

ModelBinders.Binders.Add(typeof(AccidentProtocolStep4Model), new AccidentProtocolStep4ModelBinder());

当我在调试下检查模型时,它包含空字符串,但是右结构:

[System.Web.Mvc.HttpPost]
public ActionResult AddWintess(AccidentProtocolStep4Model model)
{
    return Json(model);
}

Structure

以下是模型:

[Serializable]
public class AccidentProtocolStep4Model : IAccidentProtocolStepModel
{
    public AccidentProtocolStep4Model()
    {
        Witnesses = new List<Person>();
    }

    public List<Person> Witnesses { get; set; }
    public Person PersonToAdd { get; set; }
    public void AddPerson()
    {
        if (PersonToAdd != null && !Witnesses.Contains(PersonToAdd))
        {
            Witnesses.Add(PersonToAdd);
        }
    }

    public void RemovePerson(string lName, string fName, string mName)
    {
        Witnesses.RemoveAll(x => (x.LastName == lName && x.FirstName == fName && x.MiddleName == mName));
    }

    public void RemovePerson(int id)
    {
        Witnesses.RemoveAt(id);
    }
}

当我在调试下检查Binder时,witnessesFromRequest对象是正确的。请告诉我这里有什么问题。

更新

这是我的剃刀:

@model RAXY.Models.AccidentProtocolStep4Model
<div class="form-horizontal">
    @Html.ValidationSummary(true)

    @if (Model.Witnesses != null)
    {
        @Html.Label("Witnesses", new { @class = "control-label", @style = "padding-top: 0" })
        <p>
            <ul data-bind="foreach: allItems">
                <li data-bind="text: (FirstName + ' ' + LastName + ' ' + MiddleName) "></li>
            </ul>
        </p>

    }
</div>

<div class="form-horizontal">
    @Html.Label("Witness Name", new { @class = "control-label", @style = "padding-top: 0" })
    <div class="form-group">
        @Html.LabelFor(model => model.PersonToAdd.LastName, new { @class = "control-label col-md-6", @style = "padding-top: 0" })
        <div class="col-md-6">
            <input type="text" id="wLastName" class="witnessInput" name="LastName" />
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.PersonToAdd.FirstName, new { @class = "control-label col-md-6", @style = "padding-top: 0" })
        <div class="col-md-6">
            <input type="text" id="wFirstName" class="witnessInput" name="FirstName" />
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.PersonToAdd.MiddleName, new { @class = "control-label col-md-6", @style = "padding-top: 0" })
        <div class="col-md-6">
            <input type="text" id="wMiddleName" class="witnessInput" name="MiddleName" />
        </div>
    </div>
</div>
<div class="col-md-offset-6 col-md-6">
    <input type="button" class="btn btn-success" value="+" onclick="addWitness()" />
</div>

<script>
    function addWitness() {
        var model = {};
        $(".witnessInput").each(function () {
            model[$(this).attr("name")] = $(this).val();
        });

        $.post("AddWintess",
        {
            Witnesses: [{
                LastName: "test1",
                FirstName: "test1",
                MiddleName: "test1"
            },
            {
                LastName: "test2",
                FirstName: "test2",
                MiddleName: "test2"
            }],
            PersonToAdd: {
                LastName: $("#wLastName").val(),
                FirstName: $("#wFirstName").val(),
                MiddleName: $("#wMiddleName").val()
            }
        }, function (data) {
            my.viewModel.allItems(data.Witnesses);
        });
    }
    var my = { viewModel: new WitnessesModel() }
    function WitnessesModel() {
        var self = this;
        self.allItems = ko.observableArray([]);
        self.test = ko.computed(function () {
            var result = "";
            self.allItems().forEach(function (item) {
                result += item.LastName + " " + item.FirstName + " " + item.MiddleName + "; ";
            });
        });
    }
    ko.applyBindings(my.viewModel);
</script>

0 个答案:

没有答案