0

我的模型定义:

public class RulePageViewModel
{
    public List<RuleItem> RuleItemList { get; set; }

    public RuleViewModel RuleViewModel { get; set; }
}

我的行动定义:

public JsonResult Save(RulePageViewModel viewmodel)

我尝试发布 json,viewmodel.RuleItemList.Count > 0,但 viewmodel.RuleItemList 中的实例为空。如果使用模型绑定,如何在视图中绑定列表?

我没有尝试绑定模型,只是使用 ajax 将 json 发布到操作。我认为它会起作用,但失败了代码:

var s = { "RuleItemList": [{ "RuleGroupId": 1, "RuleGroupName": "", "Keywords": "ajax", "ResponseDescribe": "dadhsa" }], "RuleViewModel": { "RuleGroupId": 14, "RuleList": [{ "RuleId": 567, "SourceId": 125, "KeyValue": "callback", "SourceType": 0 }], "SourceList": [] } };
var ss = JSON.stringify(s);
var json = JSON.parse(ss);
$.ajax({
    url: '@Url.Action("Save")',
    type: 'POST',
    data: json,
    dataType: 'json',
    success: function(response) {
        alert('success');
    },
    error: function(jqXHR, textStatus, errorThrown) {
        alert(textStatus);
    }
});

好的,我解决了:

var json = { "RuleItemList": [{ "RuleGroupId": 1, "RuleGroupName": "", "Keywords": "ajax", "ResponseDescribe": "dadhsa" }], "RuleViewModel": { "RuleGroupId": 14, "RuleList": [{ "RuleId": 567, "SourceId": 125, "KeyValue": "callback", "SourceType": 0 }], "SourceList": [] } };

$.ajax({
    url: '@Url.Action("Save")',
    type: 'POST',
    data: JSON.stringify(json),
    dataType: 'json',
    contentType: 'application/json',
    success: function(response) {
        alert('success');
    },
    error: function(jqXHR, textStatus, errorThrown) {
        alert(textStatus);
    }
});

谢谢大家!

4

1 回答 1

0

Generally you should do something like that:

    @for(var i = 0;i<Model.RuleItemList.Count;++i)
    {
        @Html.TextBoxFor(m => m.RuleItemList[i].Name);
    }

    @Html.EditorFor(m = > m.RuleViewModel.PropertyOne);
    @Html.EditorFor(m = > m.RuleViewModel.PropertyTow);
    @Html.EditorFor(m = > m.RuleViewModel.PropertyThree);

Which will eventually generate something like that to the html:

<input type="text" name="RuleViewModel.PropertyOne" value="" />
<input type="text" name="RuleViewModel.PropertyTow" value="" />
<input type="text" name="RuleViewModel.PropertyThree" value="" />

Now because you did not place any view code or any code from your RuleItem an RuleViewModel classes that is going to be some problem to specifically answer your question so please post more info but in general you should understand from what i wrote here how to implement such a from that will post the data to your controller action so that the Model Binder will know which properties to bind..

http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx

于 2013-02-28T03:42:46.660 回答