getJSON doesnt call webAPI method - c#

Im new on mvc 4 and webAPI and Im developing my first application on it.It is single page application and using Knockoutjs.I use this walkthrough https://github.com/geersch/KnockoutSpa/
every thing is fine with my webAPI method and it return correct value when I call method with Fiddler.But it never called when I use it from getJson() method.Here is my HTML:
<table id="nqsales" class="table table-striped table-hover table-condensed">
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
</thead>
<tbody data-bind="foreach: viewModel.nqsales">
<tr>
<td data-bind="text: a"></td>
<td data-bind="text: b"></td>
<td data-bind="text: c"></td>
</tr>
</tbody>
</table>
Javascript
$(function () {
ko.applyBindings(viewModel);
viewModel.loadNqsales();
});
var viewModel = {
nqsales: ko.observableArray([]),
loadNqsales: function () {
var self = this;
$.getJSON(
'#Url.RouteUrl("DefaultApi", new { httproute = "", controller = "NQSale" })',
function (nqsales) {
self.nqsales.removeAll();
$.each(nqsales, function (index, item) {
self.nqsales.push(new nqsale(item));
});
}
);
}
};
function nqsale(nqsale) {
this.expenceFormNo = ko.observable(nqsale.a);
this.orderNo = ko.observable(nqsale.b);
this.date = ko.observable(nqsale.c);
}
WebAPIController
// GET api/NQSale
public IEnumerable<NQSaleDto> GetNQSales()
{
//return db.NQSales.AsEnumerable();
return db.NQSales
.AsEnumerable()
.Select(nqlist => new NQSaleDto(nqlist));
}

Your Url construction of
#Url.RouteUrl("DefaultApi", new { httproute = "", controller =
"NQSale" })
should generate a URL of '/api/NQSale' this means that your controller should be the following:
//The controller name relates to the route
public class NQSaleController : ApiController
{
// The action name relates to the HttpVerb
public IEnumerable<NQSaleDto> Get()
{
//return db.NQSales.AsEnumerable();
return db.NQSales
.AsEnumerable()
.Select(nqlist => new NQSaleDto(nqlist));
}
}
By default, the routing for API is that the name of the controller (NQSaleController) relates to the path and the name of the Action (Get) relates to the HttpVerb.

I would guess that your Url is not being generated correctly. If the Javascript in the View currently or in a seperate file ? #Url only works if its in the view.

Related

Update table in foreach loop with filtered model with Ajax (asp.net mvc c#)

I've developed an asp.net MVC web app where I have a table that shows some items in a model.
I can filter it now with a dropdown list using ajax
The model that i pass to the table is correct (if i go to the model before the foreach there are 3 rows instead of 10 thanks to the filter)
The problem is that the table doesn't change, it always shows all the rows as the initial request.
It look like it works but the table won't update...
There's my jquery ajax call:
$("#Dropdown1Id").on('change', function () {
//console.log("onchange");
//console.log($("#Dropdown1Id").val());
var drpdown1 = $("#Dropdown1Id").val();
var submit = $("#submitButton");
$.ajax({ // crea una chiamata AJAX
data: { data: drpdown1 }, // prendi i dati del form in questo caso del primo dropdown
type: "GET", // GET o POST
url: "/Select/Filter", // li passa al controller
success: function () { // se va con successo esegue il codice seguente
submit.click();
$("#frmId").submit();
},
error: function (error) {
console.log("error")
}
});
});
There's my controller action:
public ActionResult Filter(string data)
{
List<Card> cards = new List<Card>();
ViewBag.stato = new SelectList(myApi.GetState(), "Name", "Name");
if (data != null && data != "")
{
foreach (var card in model)
{
if (card.IdList == data || data == "")
cards.Add(card);
}
return View(cards);
}
return View(model);
}
There's my view with the daple and the dropdown:
#using (Html.BeginForm(new { id = "frmId"}))
{
#Html.AntiForgeryToken()
<table id="tb2">
<tr>
<th>
<h4> LIST : #Html.DropDownList("stato", null, new { #id = "Dropdown1Id" })</h4>
</th>
#*<th>
<h4>ARCHVIED : #Html.DropDownList("closed", null, new { #id = "Dropdown2Id" })</h4>
</th>*#
<th>
<input type="submit" value="Filter" class="btn btn-info" id="submitButton" />
</th>
</tr>
</table>
<br />
<div id="risultato"></div>
<table class="table" id="tb1">
<tr>
<th style="text-align:center">
TRELLO'S CARDS LIST
</th>
<th>LIST</th>
<th>ARCHVIED</th>
<th>Expiration date</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.IdList)
</td>
#if (item.Closed == "True")
{
<td>YES</td>
}
else
{
<td>NO</td>
}
#if (item.Due != null)
{
<td>
#Html.DisplayFor(modelItem => item.Due)
</td>
}
else
{
<td>
Not Present
</td>
}
</tr>
idList.Add(item.Id);
}
</table>
Let me get you through the execution stack and you'll understand why:
Your MVC view is loaded. When the view is returned to the frontend it is already in Html format. Check Server side rendering here
Basically it means that #foreach (var item in Model) will only execute on the server side and will not re-run when you hit an ajax call. This will only happen on a full post.
While in your page you fire up change dropdown event and the following happens:
An ajax call hit your controller
Data are being returned to the success function
Your success: function () is being executed.
A new form post occurs. See that you didn't do anything with the return data that was returned in the success: function(). You just posted back to the controller
After the post, the full view has returned ignoring any changes in the dropdown and in the data returned.
There are 2 solutions for your problem:
Do a full post and return a new view with the proper data
Write some more javascript to change the DOM inside your sucess function

Calling ajax request from asp.net razor view

How do I initiate an ajax request (calling controller action) from razor view which returns the data in JSON format?
At the moment after clicking the action link in my razor view the page does the post request which redirects the page to /actionName which of course does not exist.
I am also using jQuery but not sure how do I fetch the data from razor view which needs to be passed if I use jQuery ajax method.
ShowEventLogs.cshtml
#{ ViewBag.Title = "Event Logs"; }
#model IEnumerable
<Application.Models.EventLogs>
<table id="data-table" class="table display responsive" style="width:100%">
<thead class="thead-colored thead-light">
<tr>
<th>Time</th>
<th>Scheme</th>
<th>Serial Number</th>
<th>Batch</th>
<th>Exp Date</th>
<th>Product Code</th>
<th>Http Code</th>
<th>Is Confirmed?</th>
<th>Confirmation Date</th>
<th>Verify Pack</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>#item.Timestamp</td>
<td>#item.ProductCodeScheme</td>
<td>#item.SerialNumber</td>
<td>#item.Batch</td>
<td>#item.ExpirationDate</td>
<td>#item.ProductCode</td>
<td>#item.HttpResponseCode</td>
<td>#item.ConfirmedParsed</td>
<td>#item.ConfirmedDate</td>
if (#item.HttpResponseCode == "202")
{
<td class="text-secondary">#Html.ActionLink("Verify Pack", "VerifyPack", "Home", new { ProductCodeScheme = #item.ProductCodeScheme, ProductCode = #item.ProductCode, SerialNumber = #item.SerialNumber, Batch = #item.Batch, ExpirationDate = #item.ExpirationDate, CommandStatusCode = 0 }, new { #class = "text-info" })</td>
}
else
{
<td class="text-secondary">Not Available</td>
}
</tr>
}
</tbody>
</table>
}
Controller action
[HttpPost]
public ActionResult VerifyPack(string productCodeScheme, string productCode, string serialNumber, string batch, string expirationDate, int commandStatusCode, string orderTrackingNo = null) {
string TextAreaResult = string.Empty;
string TextAreaResultException = string.Empty;
string TextAreaResultHttpOperationCode = string.Empty;
string TextAreaResultHttpResponseCode = string.Empty;
string TextAreaResultHttpInformation = string.Empty;
string TextAreaResultHttpWarning = string.Empty;
string TextAreaResultState = string.Empty;
string RemoteIpAddress = string.Format("{0}", Request.UserHostAddress);
try {
using(SecureMediDatabase database = new SecureMediDatabase(this)) {
DatabaseFactory.setDatabase(database);
Request baseRequest = (Request) database.createRequest(Country);
ServiceThread serviceThread = new ServiceThread(0, null, Country);
serviceThread.attach(this);
baseRequest.setId(0);
baseRequest.setProductCodeScheme(productCodeScheme);
baseRequest.setRequestType(1); //single pack
baseRequest.setProductCode(productCode);
baseRequest.setSerialNumber(serialNumber);
baseRequest.setBatch(batch);
baseRequest.setExpirationDate(expirationDate);
baseRequest.setWorkstation(RemoteIpAddress);
baseRequest.setManualEntry(string.IsNullOrEmpty(expirationDate) || string.IsNullOrEmpty(batch));
if (baseRequest.isManualEntry()) {
switch (commandStatusCode) {
case 2:
case 3:
break;
default:
throw new NotSupportedException("This operation does not support manual entries!");
}
}
switch (Country) {
case "SE":
SecureMediRequestSE requestSE = (SecureMediRequestSE) baseRequest;
requestSE.setUserId(#User.Identity.Name);
requestSE.setCommandStatusCode(commandStatusCode);
requestSE.OrderTrackingNumber = orderTrackingNo;
break;
case "FI":
SecureMediRequestFI requestFI = (SecureMediRequestFI) baseRequest;
requestFI.setSubUserId(#User.Identity.Name);
break;
}
serviceThread.RunRequest(control, baseRequest, apteekki);
TextAreaResult = string.Format("{0} {1} {2} {3} {4}", baseRequest.getResponseOperationCode(), baseRequest.getHttpResponseCode(), baseRequest.getHttpInformation(), baseRequest.getHttpWarning(), baseRequest.getResponseStatusCode());
TextAreaResultHttpOperationCode = string.Format("{0}", baseRequest.getResponseOperationCode());
TextAreaResultHttpResponseCode = string.Format("{0}", baseRequest.getHttpResponseCode());
TextAreaResultHttpInformation = string.Format("{0}", baseRequest.getHttpInformation());
TextAreaResultHttpWarning = string.Format("{0}", baseRequest.getHttpWarning());
TextAreaResultState = string.Format("{0}", baseRequest.getResponseStatusCode());
}
} catch (Exception exc) {
TextAreaResultException = "Exception: " + exc.Message;
}
return Json(new {
result = TextAreaResult,
httpOperationCode = TextAreaResultHttpOperationCode,
httpResponseCode = TextAreaResultHttpResponseCode,
httpInformation = TextAreaResultHttpInformation,
httpWarning = TextAreaResultHttpWarning,
state = TextAreaResultState,
exception = TextAreaResultException,
isSuccess = TextAreaResultHttpResponseCode == "200" || TextAreaResultHttpResponseCode == "202"
});
}
Error based on the answer:
Basically #Html.ActionLink() helper renders anchor tag (<a>) with attributes and defaulted to use GET request by refreshing whole page, hence you need to add preventDefault() in order to use AJAX callback from that element. If the action method uses HTTP GET method, you can perform simple AJAX call against common class of the anchor link like this:
$('.text-info').on('click', function (e) {
e.preventDefault();
var url = $(this).attr('href');
$.get(url, function (response) {
// do something with AJAX response
});
});
However since target controller action marked as [HttpPost], you need to extract query string parameters from href attribute with additional function and use them in the AJAX call with type: 'POST' setting, or use $.post():
$('.text-info').on('click', function (e) {
e.preventDefault(); // mandatory to prevent GET request
var url = $(this).attr('href');
var pcs = getQueryStringParams(url, 'ProductCodeScheme');
var pc = getQueryStringParams(url, 'ProductCode');
var sn = getQueryStringParams(url, 'SerialNumber');
var batch = getQueryStringParams(url, 'Batch');
var expDate = getQueryStringParams(url, 'ExpirationDate');
var csc = getQueryStringParams(url, 'CommandStatusCode');
// create key-value pair for action method parameters
var obj = { ProductCodeScheme: pcs, ProductCode: pc, SerialNumber: sn, ... }
$.ajax({
type: 'POST',
url: url.split('?')[0], // URL without query string, or use '#Url.Action("VerifyPack", "Home")'
data: obj,
dataType: 'json', // expects response as JSON
success: function (response) {
// do something with AJAX response
},
error: function (xhr, status, err) {
// error handling
}
});
// just make sure that the link is not redirecting
return false;
});
function getQueryStringParams(url, name) {
return (RegExp(name + '=' + '(.+?)(&|$)').exec(url)||[,null])[1];
}
Actually there exists another way to call AJAX from anchor tag like #Ajax.ActionLink(), depending on your choice:
#Ajax.ActionLink("Verify Pack", "VerifyPack", "Home", new { ProductCodeScheme = #item.ProductCodeScheme, ProductCode = #item.ProductCode, SerialNumber = #item.SerialNumber, Batch = #item.Batch, ExpirationDate = #item.ExpirationDate, CommandStatusCode = 0 },
new AjaxOptions { HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "targetElementId",
OnComplete = "onComplete();"
},
new { #class = "text-info" })
Note:
If you need to handle AJAX request and normal request from the same controller, you can differentiate them using Request.IsAjaxRequest() (or Context.Request.Headers["X-Requested-With"] == "XMLHttpRequest" in Core MVC).
Something like this should get you started. Add a class to the items you need to pull information from. Then instead of using an actionlink just create a normal a element with a unique class as well. Have JQuery handle click events on those links and pass the other TD items of the same row to the controller via an AJAX call.
$(".button").click( function() {
var tr = $(this).closest("tr");
var ProductCodeScheme = tr.find(".ProductCodeScheme").html();
var SerialNumber = tr.find(".SerialNumber").html();
var Batch = tr.find(".Batch").html();
var ExpirationDate = tr.find(".ExpirationDate").html();
var ProductCode = tr.find(".ProductCode").html();
$.ajax({
url: "/Verify Pack/VerifyPack",
type: "POST",
data: ({
ProductCodeScheme: ProductCodeScheme,
SerialNumber: SerialNumber,
Batch: Batch,
ExpirationDate: ExpirationDate,
ProductCode: ProductCode
}),
cache: false,
success: function(data){
//Do something here for a successful POST
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="data-table" class="table display responsive" style="width:100%">
<thead class="thead-colored thead-light">
<tr>
<th>Time</th>
<th>Scheme</th>
<th>Serial Number</th>
<th>Batch</th>
<th>Exp Date</th>
<th>Product Code</th>
<th>Http Code</th>
<th>Is Confirmed?</th>
<th>Confirmation Date</th>
<th>Verify Pack</th>
</tr>
</thead>
<tbody>
<tr>
<td>Timestamp 1</td>
<td class="ProductCodeScheme">ProductCodeScheme 1</td>
<td class="SerialNumber">SerialNumber 1</td>
<td class="Batch">Batch 1</td>
<td class="ExpirationDate">ExpirationDate 1</td>
<td class="ProductCode">ProductCode 1</td>
<td>HttpResponseCode 1</td>
<td>ConfirmedParsed 1</td>
<td>ConfirmedDate 1</td>
<td class="text-secondary">Item 1</td>
</tr>
<tr>
<td>Timestamp 2</td>
<td class="ProductCodeScheme">ProductCodeScheme 2</td>
<td class="SerialNumber">SerialNumber 2</td>
<td class="Batch">Batch 2</td>
<td class="ExpirationDate">ExpirationDate2</td>
<td class="ProductCode">ProductCode 2</td>
<td>HttpResponseCode 2</td>
<td>ConfirmedParsed 2</td>
<td>ConfirmedDate 2</td>
<td class="text-secondary">Item 2</td>
</tr>
</tbody>
</table>

Change TextBox Value and Update On Ajax Call

I am working on an ecommerce site where I am stuck on the cart management. Basically before login, products are kept in a session and I am trying to update the product quantity stored in the session using Ajax. I mean whenever I write in the 'Quantity To Change', the changed value should be reflected in the 'Quantity' column.
Note: I've shortened the post and figured out why it wasn't firing while debugging. Actually I was unable to get the id of the associated product. Now it passes the id. That's it. Now I've another issue - The TextBox are being created dynamically with a for loop. I used developer tools to figure out how the TextBoxes are generated dynamically and it is something like this:
For Product 1: cartDetails_0__Quantity
For Product 2: cartDetails_1__Quantity
I am wondering how to grab the quantity or values from the dynamically generated TextBoxes. If I put the generated id from HTML directly to Ajax, then it updates the quantity. Otherwise it doesn't. I've tried to use a loop in Ajax but I think, I am getting it wrong. Please see the View.
The view:
<table border="1" width="100%" cellpadding="4">
<thead>
<tr>
<th style="text-align:center;">Name</th>
<th style="text-align:center;">Price</th>
<th style="text-align:center;">Quantity</th>
<th style="text-align:center;">Quantity To Change</th>
</tr>
</thead>
<tbody>
#if (ViewBag.CartDetails != null)
{
for (int i = 0; i < cartDetails.Count(); i++)
{
<tr>
<td style="text-align: center; display:none;">#Html.DisplayFor(model => cartDetails[i].ProductId)</td>
<td id="ID" style="text-align: center;">#Html.DisplayFor(model => cartDetails[i].ProductName)</td>
<td style="text-align: center;">#Html.DisplayFor(model => cartDetails[i].Price)</td>
<td style="text-align: center;">#Html.DisplayFor(model => cartDetails[i].Quantity, new { #class = "quantityUpdate" })</td>
<td style="text-align: center;">#Html.TextBoxFor(model => cartDetails[i].Quantity, new { #class = "quantity", data_id = cartDetails[i].ProductId } )</td>
</tr>
}
}
</tbody>
</table>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var url = '#Url.Action("UpdateCart")';
$(".quantityUpdate").change(function () {
var id = $(this).data('id');
var i = 0;
$('.quantityUpdate').each(function (i, item) {
$.post(url, { id: id, Quantity: $("#cartDetails_"+i+"__Quantity").val() }, function (response) {
if (response) {
$("#TotalPrice").load(window.location + " #TotalPrice");
}
});
})
alert(id);
alert($("#cartDetails_"+i+"__Quantity").val());
});
Here is an image sample that I am trying:
$('.quantity').change(function(){
$('.quantityUpdate').val($('.quantity').val());
// put code here
});
Instant Change
$('.quantity').keyup(function(){
$('.quantityUpdate').val($('.quantity').val());
// put code here
});
If the idea is to call ajax when you change the value in .quality textbox then this is how you should do:
$('.quantity').change(function(){
//your ajax call
});

ajax delete is going inifinite loop in asp.net mvc 4 Cannot evaluate expression because the current thread is in a stack overflow state

I have an asp.net MVC 4 application. In its _layout.cshtml, I need to show cart as partial view. So I used this:
#{Html.RenderAction("GetCart", "Home");}
and then action method:
[InitializeSimpleMembership]
[ChildActionOnly]
public ActionResult GetCart()
{
var cartItems = list of cart items
return PartialView("~/Views/shared/_Cart.cshtml", cartItems);
}
In my partial view I have this:
#foreach (var cartItem in Model)
{
<tr>
<td colspan="4">
<div id="POCStatus"></div>
</td>
</tr>
<tr>
<td class="details">
<p class="item">#cartItem.ItemName</p>
</td>
<td class="quant">#cartItem.Quantity</td>
<td class="price">
<p class="amount">#cartItem.ListPrice KD</p>
</td>
<td class="garbage"><a id="lnkDeleteCartItem" class="RemoveLink" href="#" data-id="#cartItem.CartItemID">
<img src="/images/delete.png" width="16" height="16" /></a></td>
</tr>
}
and jquery function:
$(function () {
// Document.ready -> link up remove event handler
$(".RemoveLink").click(function () {
// Get the id from the link
var recordToDelete = $(this).attr("data-id");
if (recordToDelete != '') {
// Perform the ajax post
$.post("/Home/DeleteCartItem", { "id": recordToDelete },
function (data) {
// Successful requests get here
// Update the page elements
if (data.ItemCount == 0) {
$('#row-' + data.DeleteId).fadeOut('slow');
} else {
$('#item-count-' + data.DeleteId).text(data.ItemCount);
}
$('#cart-total').text(data.CartTotal);
$('#update-message').text(data.Message);
$('#cart-status').text('Cart (' + data.CartCount + ')');
});
}
});
});
but when i click delete button, it goes to infinit loop, perhaps because of Html.action in layour.cshtml.
delete function is like this:
[HttpPost]
public ActionResult DeleteCartItem(int Id)
{
ItemBiz.DeleteItemFromCart(Id);
return Json("something");
}
Please suggest solution to this.

MVC3 fails to parse JSON

Using the following action from a MVC3 controller:
[HttpPost]
public ActionResult GetAsiguratiSuplimentari(int numarAsiguratiSuplimentari, AcpComplexAsigurat[] oldData)
{
var newData = new List<AcpComplexAsigurat>(oldData);
for(int i = newData.Count; i < numarAsiguratiSuplimentari; i++)
{
newData.Add(new AcpComplexAsigurat());
}
return PartialView("AsiguratiSuplimentari", newData);
}
and the js:
$("#NumarAsiguratiSuplimentari").change(function (e) {
var data = { oldData: $("#div-asigurati-suplimentari").find('input').serialize(), numarAsiguratiSuplimentari: $("#NumarAsiguratiSuplimentari").val() };
var postData = JSON.stringify(data);
$.post('#Url.Action("GetAsiguratiSuplimentari")', postData, function (data) {
$("#div-asigurati-suplimentari").html(data);
});
});
I want to get the select option the user chose and serialize a table of inputs to send to the above action:
<h3>Asigurati</h3>
<div class="field half odd">
<label>Numar asigurati suplimentari</label>
<select id="NumarAsiguratiSuplimentari" name="NumarAsiguratiSuplimentari">
#for (int i = 0; i <= 30; i++)
{
<option value="#i" #(Model.Asigurati.Count == i ? "selected" : "")>#i</option>
}
</select>
</div>
<div class="field full" id="div-asigurati-suplimentari">
#if (Model.Asigurati.Count > 0)
{
<table id="Asigurati">
<thead>
<tr>
<th>CNP</th>
<th>Nume</th>
<th>Prenume</th>
<th>Data nasterii</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Asigurati)
{
<tr>
<td style="padding: 3px;">#Html.TextBoxFor(x => Model.Asigurati[Model.Asigurati.IndexOf(item)].Cnp, new { maxlength = 13 })</td>
<td style="padding: 3px;">#Html.TextBoxFor(x => Model.Asigurati[Model.Asigurati.IndexOf(item)].Nume)</td>
<td style="padding: 3px;">#Html.TextBoxFor(x => Model.Asigurati[Model.Asigurati.IndexOf(item)].Prenume)</td>
<td style="padding: 3px;">#Html.TextBoxFor(x => Model.Asigurati[Model.Asigurati.IndexOf(item)].DataNastere)</td>
</tr>
}
</tbody>
</table>
}
</div>
In monorail, I would have had to decorate the input parameters with a {JsonBinder] attribute, but in MVC3 i am not sure how to proceed.
It basically gives me the following error:
The parameters dictionary contains a null entry for parameter
'numarAsiguratiSuplimentari' of non-nullable type 'System.Int32' for
method 'System.Web.Mvc.ActionResult GetAsiguratiSuplimentari(Int32,
BrokerPlatform.Services.AcpComplex.AcpComplexAsigurat[])' in
'BrokerPlatform.Areas.AcpComplex.Controllers.CarpaticaController'. An
optional parameter must be a reference type, a nullable type, or be
declared as an optional parameter. Parameter name: parameters
Here is the JSON that it sends:
{"numarAsiguratiSuplimentari":"2","oldData":""}
Parameters are inconsistent.
public ActionResult GetAsiguratiSuplimentari(int numarAsiguratiSuplimentari?, AcpComplexAsigurat[] oldData)
int? numarAsiguratiSuplimentari is nullable ?
or
$.post('#Url.Action("GetAsiguratiSuplimentari")', {numarAsiguratiSuplimentari:number,AcpComplexAsigurat:list}, function (data) {
...{numarAsiguratiSuplimentari:number,AcpComplexAsigurat:list}....
You can parse the string and get the json, and convert to model.
My sample;
[HttpPost()]
public ActionResult GetAsiguratiSuplimentari(string model)
{
List<myModel> myModel = JsonConvert.DeserializeObject<List<muModel>>(model);
}
I don't have MVC 3 right now, but this is working fine with MVC 4 (using Fiddler). There are a few things you can try:
Explicitly set dataType: "json" in the $.post call, jQuery might not be able to guess it.
Change the method signature to accept a string instead of an int, the binding in MVC 3 might not be able to do it automatically.
If one of these work, let me know so I can remove the incorrect option.

Categories