[HttpPost]
public ActionResult Charter(List<int> stateIds)
{
try
{
if (!stateIds.Any())
{
return Json("State list is empty", JsonRequestBehavior.AllowGet);
}
var states = new List<CfVersionEntities.Model.State>();
stateIds.ForEach(id =>
{
using (var db = new Storage_cfEntities())
{
var stateList = db.States.Where(i => i.Id == id).ToList();//get names of states with matching id and save in array named
if (!stateList.Any()) return;
var state = stateList[0];
states.Add(state);
}
});
return !states.Any() ? Json(new List<State>(), JsonRequestBehavior.AllowGet) : Json(states, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json(new List<State>(),
JsonRequestBehavior.AllowGet);
}
}
我有一个方法接受来自我的jquery脚本的值,如下所示,脚本工作正常并发送值,值在我的方法中接收,我已经确认。但是当我运行它时,我得到错误:ObjectContext实例已被处理,不能再用于需要连接的操作....我使用来自我的jquery的值来遍历我的数据库并选择具有的行相应的ID,我然后将此结果发送回我的jquery中的另一个函数,该函数创建一个带有值的高图
这是我的视图,其中包含我的脚本。
<p>
<h2> @Html.ActionLink("Add A New State", "CreateState")</h2>
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Stations)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Stations)
</td>
<td>
@Html.ActionLink("Update Stations", "UpdateStation", new {id = item.Id})||
<div>
<input type="checkbox" id="@item.Id" value="@item.Id" class="chk" onclick="setChecked(this)"> <label >Add to Chart</label>
</div>
</td>
</tr>
}
</table>
<div id="charts" style="width:100%" height="400px;"></div>
<input type="button" value="Verify Selections" onclick="submit()"/>
<input type="button" value ="View Chart" onclick="location.href='@Url.Action("Charter")'" />
<script type="text/javascript">
var collection = [];
function setChecked(el) {
var id = $(el).attr('id');
if ($(el).is(':checked'))
{
collection.push(id);
} else {
$.each(collection, function (item, index)
{
if (item === id)
{
collection.splice(index, 1);
}
});
}
}
function submit() {
if (collection == null || collection.length < 1) {
alert('please select at least one state.');
return;
}
$.ajax({
type: "POST",
url: '/State/Charter',
data: { stateIds: collection },
dataType: 'application/json',
success: function (response)
{
if (response.length > 0) {
designChart(response);
}
}
});
}
function designChart(response)
{
var names = [];
var stations = [];
$.each(response, function (item) {
if (item.Id > 0) {
names.push(item.Name);
stations.push(item.Stations);
}
});
$("#charts").highcharts({
chart:
{
type: 'line'
},
title: {
text: 'States'
},
xAxis: {
categories: names
},
yAxis:
{
title:
{
text: 'Stations',
categories: stations
}
}
});
}
</script>