我有一个非常大的模型列表,我想使用ajax查询将该列表发送回控制器。我尝试将整个模型列表发送回去,但是由于模型太大,它超出了web.config中指定的json maxlength。虽然编码方法适用于较小的列表。
var jsonString = @Html.Raw(Json.Encode(Model.modelName_small));
我可以想象它起作用的唯一方法是使用JavaScript将大型模型列表过滤为较小的列表(类似于“ Where” SQL语句)。我的脚本如下(剃刀):
<script type="text/javascript" language="javascript">
function functionName(input1_decimal) {
var smallerList = new Array();
@foreach (var item in Model.modelName)
{
//input1_decimal should be within a certain range
@:if (input1_decimal - 0.1 <= @item.Property1) && (@item.Property1 <= input1_decimal + 0.1)
{
@:smallerList.push("@item");
}
}
//convert smallerList to json and send it to controller
}
<script>
这似乎很简单,但我无法使其正常工作。可能有些琐碎。我也尝试过:
var smallerList= Model.modelName.Where(x => (input1_decimal - 0.1 <= x.Property1) && (x.Property1 <= input1_decimal + 0.1));
类似地,我也尝试过
var smallerList = Model.modelName.filter(function (item) {
return (input1_decimal - 0.1 <= item.Property1) && (item.Property1<= input1_decimal + 0.1)
});
感谢您的耐心配合。我希望我已经清楚地解释了我要达到的目标。我不是开发人员。编程只是为了娱乐和自我教育。
答案 0 :(得分:0)
您是否正在修改视图上的数据?如果是这样,另一种方法是仅将修改后的数据发布到控制器,以最小化json字符串的长度,并直接在控制器中检索其余数据。
答案 1 :(得分:0)
我没有在web.config中编辑jsonmaxlength字段,而是将MaxJsonLength分配给Int32.MaxValue。创建一个列表并分配属性以对模型属性进行建模并序列化为Json对象列表。然后我使用$ .grep函数过滤了列表。终于,我能够将objJsonSmallList发送回控制器了……开心的日子:)
@{
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
js.MaxJsonLength = Int32.MaxValue;
//Create a list and assigning all the properties of the model
var data = Model.model_Name.Select(x => new
{
propName1 = x.property1,
propName2 = x.property2,
...
propNameN = x.propertyN
});
//serialize collection of anonymous objects
string strArr = js.Serialize(data);
}
var objJsonBigList = JSON.parse('@strArr'.replace(/"/g, '"'));
//small Filtered list send to controller via Ajax
var objJsonSmallList = $.grep(objJsonBigList, function (n) {
return ((input1_decimal- 0.1 <= n.Prop) && (n.Prop <= input1_decimal + 0.1))
});