Remove From Cart operation not rendering anything - c#

I got an issue with my Ajax. When I clicked on the Remove From Cart, The ajax seems not rendering anything. Any hint? Here is my code:
Index.cshtml
#model Tp1WebStore3.ViewModels.ShoppingCartViewModel
#{
ViewBag.Title = "Shopping Cart";
}
<script src="/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('.RemoveLink').click(function () {
$.ajax({
url: '/Panier/RemoveFromCart',
data: { id: $(this).data('id') },
cache: false,
success: function (result) {
$('#row-' + result.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + result.CartCount + ')');
$('#update-message').text(result.Message);
$('#cart-total').text(result.CartTotal);
}
});
return false;
});
});
</script>
<h3>
<em>Details</em> du panier:
</h3>
<p class="button">
#Html.ActionLink("Checkout >>", "AddressAndPayment", "Checkout")
</p>
<div id="update-message">
</div>
<table>
<tr>
<th>
Produit
</th>
<th>
Prix (unitaire)
</th>
<th>
Quantite
</th>
<th></th>
</tr>
#foreach (var item in Model.CartItems)
{
<tr id="row-#item.ProduitId">
<td>
#Html.ActionLink(item.Produit.Description,"Details", "Panier", new { id =
item.ProduitId }, null)
</td>
<td>
#item.Produit.Prix
</td>
<td id="item-count-#item.ProduitId">
#item.Quantite
</td>
<td>
Remove From Cart
</td>
</tr>
}
<tr>
<td>
Total
</td>
<td></td>
<td></td>
<td id="cart-total">
#Model.CartTotal
</td>
</tr>
</table>
PanierController.cs
// AJAX: /ShoppingCart/RemoveFromCart/5
[HttpPost]
public ActionResult RemoveFromCart(int id)
{
// Remove the item from the cart
var cart = ShoppingCart.GetCart(this.HttpContext);
// Get the name of the album to display confirmation
string produitDescription = dbProduit.Paniers
.Single(item => item.PanierId == id).Produit.Description;
// Remove from cart
int itemCount = cart.RemoveFromCart(id);
// Display the confirmation message
var results = new ShoppingCartRemoveViewModel
{
Message = Server.HtmlEncode(produitDescription) +
" has been removed from your shopping cart.",
CartTotal = cart.GetTotal(),
CartCount = cart.GetCount(),
ItemCount = itemCount,
DeleteId = id
};
return Json(results);
ShoppingCart.cs
public int RemoveFromCart(int id)
{
// Get the cart
var cartItem = db.Paniers.Single(
cart => cart.CartId == ShoppingCartId
&& cart.ProduitId == id);
int itemCount = 0;
if (cartItem != null)
{
if (cartItem.Quantite > 1)
{
cartItem.Quantite--;
itemCount = cartItem.Quantite;
}
else
{
db.Paniers.Remove(cartItem);
}
// Save changes
db.SaveChanges();
}
return itemCount;
Here is the Chrome output PF12 for the network tab

Change:
$.ajax({
url: '/Panier/RemoveFromCart',
data: { id: $(this).data('id') },
cache: false,
success: function (result) {
$('#row-' + result.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + result.CartCount + ')');
$('#update-message').text(result.Message);
$('#cart-total').text(result.CartTotal);
}
To:
$.ajax({
url: '/Panier/RemoveFromCart',
data: { id: $(this).data('id') },
type: 'POST',
cache: false,
success: function (result) {
$('#row-' + result.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + result.CartCount + ')');
$('#update-message').text(result.Message);
$('#cart-total').text(result.CartTotal);
}
Another option, although not recommended is to remove the [HttpPost] from the top of your controller. This will raise other issues for you, as the recommended way to send data using ajax is 'POST'

Related

Ajax & ASP.NET MVC : get data by ID without using Entity Framework

I am trying to get data in my DataTable by ID, the data row coming from SQL Server to my controller but I am confused: how to pass this data to my DataTable in view?
I am using this code - my model:
public class EmployeesModel
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public int Age { get; set; }
public string Position { get; set; }
public string Office { get; set; }
[Required(ErrorMessage ="Please enter date")]
public DateTime HiringDate { get; set; }
public int Salary { get; set; }
}
My controller
public JsonResult GetEmpByID(int id)
{
List<EmployeesModel> employeeList = new List<EmployeesModel>();
string CS = ConfigurationManager.ConnectionStrings["SQLConn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SP_GetEmpByID", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#EmpID", SqlDbType.NVarChar).Value = id; //Added Parameter
conn.Open();
// Get
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
EmployeesModel employee = new EmployeesModel();
employee.EmployeeId = Convert.ToInt32(reader["EmployeeId"]);
employee.Name = reader["Name"].ToString();
employee.Gender = reader["Gender"].ToString();
employee.Age = Convert.ToInt32(reader["Age"]);
employee.Position = reader["Position"].ToString();
employee.Office = reader["Office"].ToString();
employee.HiringDate = Convert.ToDateTime(reader["HiringDate"]);
employee.Salary = Convert.ToInt32(reader["Salary"]);
employeeList.Add(employee);
}
}
//return View(employeeList); Commented out
//return RedirectToAction("GetEmpByID"); Commented out
return Json(new { data = employeeList }, JsonRequestBehavior.AllowGet);
}
My view
#model IEnumerable<SQLWithoutEF.EmployeesModel>
<input type="text" id="tablename" /> //Here I enter Employee ID and below is button
<asp:Button runat="server" Text="Button" class="btn btn-danger" id="IDbtn" onclick="GetByName($('#tablename').val())">Get Data By ID</asp:Button>
#*Data Table ==============*#
<table class="table table-bordered table-responsive table-hover" id="MyTable">
<thead>
<tr>
<th style="display:none">#Html.DisplayNameFor(m => m.EmployeeId)</th>
<th>#Html.DisplayNameFor(m => m.Name)</th>
<th>#Html.DisplayNameFor(m => m.Gender)</th>
<th>#Html.DisplayNameFor(m => m.Age)</th>
<th>#Html.DisplayNameFor(m => m.Position)</th>
<th>#Html.DisplayNameFor(m => m.Office)</th>
<th>#Html.DisplayNameFor(m => m.HiringDate)</th>
<th>#Html.DisplayNameFor(m => m.Salary)</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach (var employee1 in Model)
{
<tr>
<td style="display:none">#employee1.EmployeeId</td>
<td>#employee1.Name</td>
<td>#employee1.Gender</td>
<td>#employee1.Age</td>
<td>#employee1.Position</td>
<td>#employee1.Office</td>
<td>
#if (employee1.HiringDate != null)
{
#employee1.HiringDate
}
</td>
<td>#employee1.Salary</td>
<td>
<asp:button class="btn btn-info btn-xs updbtn1">UpdateEmp</asp:button> |
<asp:button class="btn btn-danger btn-xs" data-name="#employee1.Name" id="deletebtn" onclick="deleteF(#employee1.EmployeeId)">DeleteEmp</asp:button>
</td>
</tr>
}
</tbody>
</table>
My jQuery / Ajax - here I need help:
function GetByName(id) {
if (confirm("Are You Sure to Get " + id + " " + " ?")) {
$('#MyTable tbody tr').remove();
$.ajax({
type: "GET",
url: '/Home/GetEmpByID?id=' + id,
//data: JSON.stringify({ id: id }),
//contentType: application/json, charset: utf-8,
processData: false,
dataType: 'json',
bprocessing: true,
success: function (data) { // Till here data coming but it's not working further
var items = '';
$.each(data, function (item) {
debugger;
var rows = '';
for (var i = 0; i < item.length[0]; i++) {
rows = "<tr><td>" + data + "</td>"
+ '<td><asp:button class="btn btn-info btn-xs updbtn1">UpdateEmp</asp:button> | <asp:button class="btn btn-danger btn-xs" data-name="#employee1.Name" id="deletebtn" onclick="deleteF(#employee1.EmployeeId)">DeleteEmp</asp:button></td>'
"</tr>";
$('#MyTable tbody').append(rows);
}
})
},
}).catch(function (xhr, status, error) {
var errorMeassage = xhr.status + ': ' + xhr.statusText;
alert('Error - ' + errorMeassage);
})
};
};
Here is the screenshot what output I am getting
enter image description here
Kindly suggest how I can send data from my controller to my DataTable using Ajax?
Thanks
From the controller API action,
return Json(new { data = employeeList }, JsonRequestBehavior.AllowGet);
It will return the response with body as an object with data property which contains the array, instead of the response is the array.
The response body would be as:
{
data: [/* Employee List */]
}
In JavaScript part, to take the employee array
var items = data.data;
The implementation in success callback should be:
var items = data.data;
$.each(items, function (index, item) {
debugger;
var rows = '';
rows = `<tr>
<td style="display:none">${item.EmployeeId}</td>
<td>${item.Name}</td>
<td>${item.Gender}</td>
<td>${item.Age}</td>
<td>${item.Position}</td>
<td>${item.Office}</td>
<td>${item.HiringDate}
</td>
<td>${item.Salary}</td>
<td><asp:button class="btn btn-info btn-xs updbtn1">UpdateEmp</asp:button> | <asp:button class="btn btn-danger btn-xs" data-name="${item.Name}" id="deletebtn" onclick="deleteF(${item.EmployeeId}">DeleteEmp</asp:button></td>
</tr>`;
$('#MyTable tbody').append(rows);
})
Note: You may use the string interpolation / template literal which makes it easier to build the template string.
Demo

ajax post does not return view data

I am using ajax post to call controller method DeviceData(). It does not return view data.
When I try to debug the code ,values are assigned to viewBag both in controller.cs and .cshtml but browser displays no data. Code does not return any error. After ajax call it only shows patientDDL.
I need to display "deviceName date etc.." which I assigned in viewBag.
This is my code:
DeviceData.cshtml
#model Hospital.Models.DeviceModel
<div class="row">
<div class="col-md-12">
<div id="pdf" class="pull-left">
<table>
<tr>
<td class="blue-bgcolor">Patient List : </td>
<td>
#Html.DropDownList("FromJson", new SelectList(Enumerable.Empty <SelectListItem>()),"select",
new { Class = "form-control", onchange = "SelectedIndexChanged()" })
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="row">
<table class="table valign-middle">
<tbody>
<tr>
<td>Device Name</td>
<td>#ViewBag.deviceName</td>
</tr>
<tr>
<td>DateTime</td>
<td>#ViewBag.date</td>
</tr>
<tr>
<td>SPO2</td>
<td>#ViewBag.spo2</td>
</tr>
<tr>
<td>PR</td>
<td>#ViewBag.pr</td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: "PatinetDDl",
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: JSON,
success: function(result) {
$(result).each(function() {
$("#FromJson").append($("<option></option>").val(this.Value).html(this.Text));
});
},
error: function(data) {}
});
});
</script>
<script type="text/javascript">
function SelectedIndexChanged() {
var pid = $("#FromJson").val();
alert(pid);
$.ajax({
url: '/Data/DeviceData',
type: 'POST',
datatype: 'json',
//contentType: 'application/json',
data: { pid: +pid },
success: function (result) { },
error: function () { alert("Whooaaa! Something went wrong..") },
});
}
</script>
Datacontroller.cs
public JsonResult PatinetDDl()
{
Common.DBConnect.fnconchk(con);
DataTable dtpatient = new DataTable();
string query = "";
query = "select Preg_id,P_Name from Patient_Reg";
SqlCommand cmd2 = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd2);
da.Fill(dtpatient);
List<SelectListItem> ObjList = new List<SelectListItem>();
foreach (DataRow row in dtpatient.Rows)
{
ObjList.Add(new SelectListItem()
{
Text = row["P_Name"].ToString(),
Value = row["Preg_id"].ToString()
});
}
var jsonData = ObjList;
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult DeviceData()
{
DeviceModel obj = new DeviceModel();
return View(obj);
}
[HttpPost]
public ActionResult DeviceData(string pid)
{
DeviceModel obj = new DeviceModel();
DataTable dt = new DataTable();
Common.DBConnect.fnconchk(con);
if (pid != null)
{
string query = "";
query = " select D_Name,Date_Time,D_Value1 from readings where pid='" + pid;
SqlCommand cmd2 = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd2);
da.Fill(dt);
ViewBag.deviceName = dt.Rows[0]["D_Name"].ToString();
ViewBag.date = dt.Rows[0]["Date_Time"].ToString();
ViewBag.spo2 = dt.Rows[0]["D_Value1"].ToString();
ViewBag.pr = dt.Rows[0]["D_Value2"].ToString();
}
return View(obj);
}
Many things you want to change to get the desire output.
First
make a partial view name _deviceInfo.cshtml
<table class="table valign-middle">
<tbody>
<tr>
<td>Device Name</td>
<td>#ViewBag.deviceName</td>
</tr>
<tr>
<td>DateTime</td>
<td>#ViewBag.date</td>
</tr>
<tr>
<td>SPO2</td>
<td>#ViewBag.spo2</td>
</tr>
<tr>
<td>PR</td>
<td>#ViewBag.pr</td>
</tr>
</tbody>
</table>
Second
Changing in your controller action method
[HttpPost]
public PartialViewResult DeviceData(string pid)
{
DeviceModel obj = new DeviceModel();
DataTable dt = new DataTable();
Common.DBConnect.fnconchk(con);
if (pid != null)
{
string query = "";
query = " select D_Name,Date_Time,D_Value1 from readings where pid='" + pid;
SqlCommand cmd2 = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd2);
da.Fill(dt);
ViewBag.deviceName = dt.Rows[0]["D_Name"].ToString();
ViewBag.date = dt.Rows[0]["Date_Time"].ToString();
ViewBag.spo2 = dt.Rows[0]["D_Value1"].ToString();
ViewBag.pr = dt.Rows[0]["D_Value2"].ToString();
}
return PartialView(obj);
}
Third
Ajax Method in DeviceData.cshtml
#model Hospital.Models.DeviceModel
<div class="row">
<div class="col-md-12">
<div id="pdf" class="pull-left">
<table>
<tr>
<td class="blue-bgcolor">Patient List : </td>
<td>
#Html.DropDownList("FromJson", new SelectList(Enumerable.Empty <SelectListItem>()),"select",
new { Class = "form-control", onchange = "SelectedIndexChanged()" })
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="row" id="device-data">
</div>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: "PatinetDDl",
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: JSON,
success: function(result) {
$(result).each(function() {
$("#FromJson").append($("<option></option>").val(this.Value).html(this.Text));
});
},
error: function(data) {}
});
});
</script>
<script type="text/javascript">
function SelectedIndexChanged() {
var pid = $("#FromJson").val();
alert(pid);
$.ajax({
url: '/Data/DeviceData',
type: 'POST',
datatype: 'html',
//contentType: 'application/json',
data: { pid: +pid },
success: function (result) {
$('#device-data').html(result);
},
error: function () { alert("Whooaaa! Something went wrong..") },
});
}
</script>
Hope it will work for you :)
The Problem is you return a view by action result (html) but you have used data type json in your second ajax script.
Edit SelectedIndexChanged like this :
function SelectedIndexChanged() {
var pid = $("#FromJson").val();
alert(pid);
$.ajax({
url: '/Data/DeviceData',
type: 'POST',
datatype: 'html',
//contentType: 'application/json',
data: { pid: +pid },
success: function (data) {
$('#placeHolder').html(data);
},
error: function () { alert("Whooaaa! Something went wrong..") },
});
}
Don't forget to add placeHolder element where ever you want to show the DeviceData:
<div id="#placeHolder"></div>

How to reload datatable in jquery using mvc

I have a function and get the response from the controller.after that I need to append the details to the table.All I have done.But i can see the result only after I click the table .I think my datatable is not reloaded.How Can I solve this problem.My code is below.and html code is added here.When the select box changes according to the result the table is updated
$(document).on('change', '.MemberSelect', function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ memberTypeID: $(".MemberSelect").val() }),
url: "#Url.Action("GetUserMenuDetails", "MenuPermission")",
success: function (data) {
var trHtml = '';
$('#tblClassName tbody').empty();
$.each(data, function (i, item) {
trHtml = trHtml + '<tr><td></td><td>' + (item.LibrarySchooberryMenuDetails!=null? item.LibrarySchooberryMenuDetails.MenuName : "") + '</td>'
'<td>' + item.MenuName + '</td>'
'<td><input type="checkbox" class="MenuMap" id="' + item.MenuID + '" data-id="' + item.MenuID + '"/></td>'
'<td><table>';
$.each(data.LibrarySchooberryMenuFunctions, function (j, functions) {
trHtml = trHtml + '<tr><td><input type="checkbox" class="FunctionMap" id="' + functions.MenuFunctionID + '" data-id="' + functions.MenuFunctionID + '"/>'
+ functions.Name + '<input type="hidden" value="' + functions.MenuID + '" class="menuID" /></td></tr>'
});
trHtml = trHtml + '</table></td></tr>'
});
$('#tblClassName').append(trHtml);
$('#tblClassName').DataTable({
'paging': true,
'lengthChange': false,
'searching': true,
'ordering': true,
'info': true,
'autoWidth': false
});
},
error: function (data) {
}
});
return false;
});
<div class="box-body">
<form id="MenuPermission">
<div class="form-group">
<select class="form-control MemberSelect" name="MemberType"></select>
</div>
<div id="example1_wrapper" class="dataTables_wrapper form-inline dt-bootstrap">
<table class="table table-bordered table-striped" id="tblClassName">
<thead>
<tr>
<th>Sl.NO
</th>
<th>Parent Menu
</th>
<th>Menu
</th>
<th>Is Allowed
</th>
<th>Function</th>
</tr>
</thead>
<tbody>
#{
int i = 1;
foreach (var item in Model)
{
<tr>
<td>#i
</td>
<td>
#Html.DisplayFor(modelItem => item.LibrarySchooberryMenuDetails.MenuName)
</td>
<td>
#Html.DisplayFor(modelItem => item.MenuName)
</td>
<td>
<input type="checkbox" class="MenuMap" id="#item.MenuID" data-id="#item.MenuID"/>
</td>
<td>
<table>
#foreach (var function in item.LibrarySchooberryMenuFunctions)
{
<tr>
<td>
<input type="checkbox" class="FunctionMap" id="#function.MenuFunctionID" data-id="#function.MenuFunctionID"/>
#function.Name
<input type="hidden" value="#function.MenuID" class="menuID" />
</td>
</tr>
}
</table>
</td>
</tr>
}
}
</tbody>
</table>
</div>
</form>
</div>
Refer to my answer here;
How to append ajax result in modal with datatable
First store the initialization to a variable, be sure to put this on the top of the script or inside a $(document).ready(function(){});
var dataTable = $('#tblClassName').DataTable({});
Instead of using jquery append to the table, you have to use the .add() function from the datatable object, then .draw() for refresh;
dataTable.row.Add().draw();
UPDATE:
dataTable.row.add($(trHtml)).draw();
To clear the datatable, use .clear() .
dataTable.clear();
Use this script;
$(document).ready(function(){
var dataTable = $('#tblClassName').DataTable({
'paging': true,
'lengthChange': false,
'searching': true,
'ordering': true,
'info': true,
'autoWidth': false
});
});
$(document).on('change', '.MemberSelect', function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ memberTypeID: $(".MemberSelect").val() }),
url: "#Url.Action("GetUserMenuDetails", "MenuPermission")",
success: function (data) {
var trHtml = '';
// revised //////////////////////
dataTable.clear();
/////////////////////////////////
$.each(data, function (i, item) {
trHtml = trHtml + '<tr><td></td><td>' + (item.LibrarySchooberryMenuDetails!=null? item.LibrarySchooberryMenuDetails.MenuName : "") + '</td>'
'<td>' + item.MenuName + '</td>'
'<td><input type="checkbox" class="MenuMap" id="' + item.MenuID + '" data-id="' + item.MenuID + '"/></td>'
'<td><table>';
$.each(data.LibrarySchooberryMenuFunctions, function (j, functions) {
trHtml = trHtml + '<tr><td><input type="checkbox" class="FunctionMap" id="' + functions.MenuFunctionID + '" data-id="' + functions.MenuFunctionID + '"/>'
+ functions.Name + '<input type="hidden" value="' + functions.MenuID + '" class="menuID" /></td></tr>'
});
trHtml = trHtml + '</table></td></tr>'
});
// revised //////////////////////
dataTable.row.add($(trHtml)).draw();
/////////////////////////////////
},
error: function (data) {
}
});
return false;
});

Cascading dropdownlist does not pass value

I am newbie in asp.net mvc.
I have 2 cascading dropdownlist and 1 file input on my page.
I made cascading dropdownlists following this tutorial. But when I trying to pass value to controller, there is an error System.ArgumentException, null parameter. I looked up the list of parameters using Firebug, but I can't find value of second dropdown at all.
My controller code is below:
public ActionResult Index()
{
List<SelectListItem> branchNames = new List<SelectListItem>();
FormatModel fmtModel = new FormatModel();
List<branch> branches = db.branch.ToList();
branches.ForEach(x =>
{
branchNames.Add(new SelectListItem { Text = x.name, Value = x.id.ToString() });
}
);
fmtModel.BranchNames = branchNames;
return View(fmtModel);
}
[HttpPost]
public ActionResult GetPaymentSystem(string branchId)
{
int intBranchId;
List<SelectListItem> paymentSystemNames = new List<SelectListItem>();
if (!string.IsNullOrEmpty(branchId))
{
intBranchId = Convert.ToInt32(branchId);
List<paymentSysDTO> paymentSystems =
(from ps in db.paymentSys
join ps_br in db.br_ps_format on ps.id equals ps_br.ps_id
join br in db.branch on ps_br.branch_id equals br.id
where br.id == intBranchId
select new paymentSysDTO
{
id = ps.id,
name = ps.name,
code = ps.code
}
).ToList();
paymentSystems.ForEach(x =>
{
paymentSystemNames.Add(new SelectListItem { Text = x.name, Value = x.id.ToString() });
}
);
}
return Json(paymentSystemNames, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult Index(int BranchNames, int PaymentSystemNames, HttpPostedFileBase file)
{
//controller code
}
View code:
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<legend>Введите данные:</legend>
<table>
<tr>
<td>
<label>Филиал</label>
</td>
<td>
#Html.DropDownListFor(x => x.BranchNames, Model.BranchNames, "Выбрать", new { id = "ddlBranch" })
</td>
</tr>
<tr>
<td>
<label>Платежная система/Банк</label>
</td>
<td id="PaymentSystem">
#Html.DropDownListFor(x => x.PaymentSystemNames, new List<SelectListItem>(), "Выбрать", new { #id = "ddlPaymentSystem" })
</td>
</tr>
<tr>
<td>
<input id="InputFile" type="file" name="file" />
</td>
</tr>
<tr>
<td>
<input id="ConvertButton" type="submit" value="Конвертировать" />
</td>
</tr>
</table>
}
#if (null != TempData["msg"])
{
#Html.Raw(TempData["msg"])
}
<script type="text/javascript">
$(function () {
$('#ddlBranch').change(function () {
$.ajax({
type: 'POST',
url: "/Home/GetPaymentSystem",
data: { branchID: $('#ddlBranch').val() },
datatype: "json",
traditional: true,
success: function (data) {
var paymentSystem = "<select id='ddlPaymentSystem'>";
paymentSystem = paymentSystem + '<option value ="">Select</option>';
for (var i = 0; i < data.length; i++)
{
paymentSystem = paymentSystem + '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
}
paymentSystem = paymentSystem + '</select>';
$('#PaymentSystem').html(paymentSystem);
}
cas
});
});
});
</script>
Sorry for my English and thanks for ur help.

how to deal with objectcontext instance has been disposed

[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);
}
}
I have a method that accepts values from my jquery scripts which is below, the script works fine and sends the values, the values are received in my method, i have confirmed that. but when i run it i get the error :The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.... I am using the values from my jquery to loop through my database and select rows that have corresponding IDs, i am then sending this result back to another function in my jquery which creates a highchart with the values
This is my View which includes my script.
List Of States
<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>

Categories