Passing JSON to WebApi in MVC5 - c#

im facing issues in syntax to pass json array from jquery to the webapi in my mvc5 project .
Following is my code :-
C# code:-
//GET Instance
// GET: api/PostDatas
public IQueryable<PostData> GetPostDatas()
{
return db.PostDatas;
}
//POST Instance
// POST: api/PostDatas
[ResponseType(typeof(PostData))]
public IHttpActionResult PostPostData(PostData postData)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.PostDatas.Add(postData);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = postData.postDataID }, postData);
}
JQuery
<script>
function fnpostdata() {
var model = {
"userid": "01",
"Description": "Desc",
"photoid": "03"
};
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/api/PostDatas/",
data: model,
success: function (data) {
alert('success');
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
}
});
}
</script>
Im not able to send the data using jquery to my c# controller , just need to understand the syntax . Thank you .

check following things in your code:
1) Method attribute [HttpPost]
2) [FromBody] for input model
3) Check PostData class, it should contain public properties for userid, Description and photoid with case-sensitive of variable names.
and mainly change your AJAX request code to:
function fnpostdata() {
var model = {
"userid": "01",
"Description": "Desc",
"photoid": "03"
};
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/api/PostDatas/",
data: JSON.stringify(model), //i have added JSON.stringify here
success: function (data) {
alert('success');
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
}
});
}
Please let me know, is this works for you?

I included [FromBody] in the parameter in my previous project.
Something like this:
[HttpPost]
public IHttpActionResult Register([FromBody]PostData postData)
{
// some codes here
}
I was able to read the JSON data from that notation.

Related

Trouble sending JSON data to another action in asp.net MVC controller

I have this controller action:
[HttpPost]
public ActionResult OrderData(Order order)
{
var result = new { redirectToUrl = Url.Action("SeatSelection", "Orders", new { id = order.ScreeningId }), order };
return Json(result);
}
and I'm trying to pass the order object to another action:
public ActionResult SeatSelection(int id, Order order)
{
var screeningInDb = _context.Screenings.Include(s => s.Seats).Single(s => s.Id == order.ScreeningId);
var viewModel = new SeatSelectionViewModel
{
Seats = screeningInDb.Seats,
NumberOfTicketsOrdered = order.NumberOfTicketsOrdered
};
return View("SeatSelection", viewModel);
}
The problem is - the only parameter I'm receiving in SeatSelection Action is the id parameter, although the order object in OrderData Action is valid. I'm pretty sure the problem is within the way I'm trying to pass the order object, maybe something with the syntax?
Here is the way I'm posting my form data to the OrderData Action:
$.ajax({
type: "POST",
url: '#Url.Action("OrderData", "Orders")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(orderData),
dataType: "json",
success: function (res) {
alert("Success!");
window.location.href = res.redirectToUrl;
},
error: function (xhr, status, error) {
alert(status);
}
});
Bottom line - What I'm eventually trying to do is to pass the form to a Controller Action where the data will be processed, and then pass the new data to "SeatSelection" view. I had trouble doing this as my post method sends JSON data, so if there is a better way to do what I'm trying to do, I would be happy to learn!
Your model doesn't match SeatSelection parameter signature.
Try:
$.ajax({
type: "POST",
url: '#Url.Action("OrderData", "Orders")',
contentType: "application/json; charset=utf-8",
data: `{"order": ${JSON.stringify(orderData)}}`,
dataType: "json",
success: function (res) {
alert("Success!");
window.location.href = res.redirectToUrl;
},
error: function (xhr, status, error) {
alert(status);
}
});
or (this one just creates a javascript object, which has the two signature properties in):
const sendObj = { id: 0, order: orderData };
$.ajax({
type: "POST",
url: '#Url.Action("OrderData", "Orders")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(sendObj),
dataType: "json",
success: function (res) {
alert("Success!");
window.location.href = res.redirectToUrl;
},
error: function (xhr, status, error) {
alert(status);
}
});
you can't use
window.location.href = ...
because in this case browser always calls a GET method that can only keep data in a query string with primitives parameters and it doesn't convert Order to a qusery string parameters. This is why you can get only id.
in your case it would be much easier to redirect directly in the action
public ActionResult OrderData(Order order)
{
return RedirectToAction( ( "SeatSelection", "Orders", new { id = order.ScreeningId }), order });
}
or when it is the same controller I usually do this
public ActionResult OrderData(Order order)
{
return SeatSelection (order.ScreeningId, order };
}
but since you are using ajax it will redirect, but will not update your view. For ajax you need a partial view that should be updated on success. So instead of ajax you can only submit form using button. In this case everything will be working ok.
Another way you can use ajax is you can try to split the order in properties and create a query string.

Ajax not hitting controller method

I have the following jquery function which is sending data to a controller:
function bound(e) {
var ele = document.getElementsByClassName("e-grid")[0]
ele.addEventListener('click', function (e) {
if (e.target.classList.contains('e-up')) {
var grid = document.getElementById('FlatGrid').ej2_instances[0]; //Grid Instance
var rowObj = grid.getRowObjectFromUID(ej.base.closest(e.target, '.e-row').getAttribute('data-uid'));
var data = rowObj.data;
//alert(JSON.stringify(data));
var code = data.ClientCode;
$.ajax({
type: "POST",
url: "/Client/ShowClient",
data: { "ClientCode": code }, //First item has latest ID
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});
}
});
}
And my controller method:
[HttpPost]
public ActionResult ShowClient(string ClientCode)
{
if (ClientCode == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
*action*
}
However I am getting a 500 (Internal Server Error) error for this. Any idea what I am missing cause my method is not being hit at all.
And I can see that var code does have the correct string value.
Remove commas from the parameter name "ClientCode" and contentType and will be work
$.ajax({
type: "POST",
url: "/Client/ShowClient",
data: { ClientCode: code }, //First item has latest ID
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});
The comments have provided you with a combination of suggestions that when put together will give you the desired behavior.
First, you can build the URL in teh view using #Url.Action
url: '#(Url.Action("ShowClient","Client"))',
Next, the object model is not being built correctly
data: { ClientCode: code },
Note the last of quotes around the key.
And finally remove the JSON content type.
Which results to portion of code.
$.ajax({
type: "POST",
url: '#(Url.Action("ShowClient","Client"))',
data: { ClientCode: code },
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});
Change the url to this:
url: "../Client/ShowClient"

Map Json data to an object using AJAX and C#

how can I use the Json formatted data sent by an AJAX request in C#?
Here's the View with the JQuery and AJAX
<script type="text/javascript">
$(function () {
$("#btnGet").click(function () {
var values =
{
"Name": "Manuel Andrade",
"DateOfBirth": "12/01/1995"
}
$.ajax({
type: "POST",
url: "/api/WebApi/GetAge",
data: values,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Hello: " + response.Name + ".\nCurrent Date and Time: " + response.DateTime);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
Here's the Controller:
public class PersonController : ApiController
{
[System.Web.Http.Route("api/WebApi/GetAge")]
[System.Web.Http.HttpPost]
public Person GetAge(Person person)
{
//person = new Person();
//person.Name = "Luis";
JsonTest(person);
//int ageInMonths = calculateAgeInMonths(person);
//int ageInYears = calculateAgeInYears(person);
//System.Diagnostics.Debug.WriteLine(ageInMonths);
//System.Diagnostics.Debug.WriteLine(ageInYears);
return person;
}
}
The Person Model has exactly the same attributes as the Json variable in the view. Shouldn't it create an object automatically? The method JsonTest() works properly, it is used to serialize the data. If I uncomment the person instantiation and assignation to Luis the method does return a Json with that data to the view. But if I try to use the person parameter just like that it throws a null Exception. How can I pass the var values in the View to the GetAge method so I can assign it to an object?
It worked fine for me when I removed the contentType: "application/json; charset=utf-8", line.
It isn't returned as application/json by default.

Post a string to mvc

I've seen how I can serialize to an object in JSON. How can I POST a string which returns a ViewResult?
$.ajax({
url: url,
dataType: 'html',
data: $(this).val(), //$(this) is an html textarea
type: 'POST',
success: function (data) {
$("#report").html(data);
},
error: function (data) {
$("#report").html('An Error occured. Invalid characters include \'<\'. Error: ' + data);
}
});
MVC
[HttpPost]
public ActionResult SomeReport(string input)
{
var model = new ReportBL();
var report = model.Process(input);
return View(report);
}
How about:
$.ajax({
url: url,
dataType: 'html',
data: {input: $(this).val()}, //$(this) is an html textarea
type: 'POST',
success: function (data) {
$("#report").html(data);
},
error: function (data) {
$("#report").html('An Error occured. Invalid characters include \'<\'. Error: ' + data);
}
});
If you make the data a JSON object with a key that matches the parameter name MVC should pick it up.
On the MVC side...
[HttpPost]
public ActionResult SomeReport()
{
string input = Request["input"];
var model = new ReportBL();
var report = model.Process(input);
return View(report);
}
You might want to return your result as a json format. Not sure how to exactly do this with asp.net, but if it were Rails, it would be return #foo.to_json
You need to add a contentType. Look at the jQuery API:
http://api.jquery.com/jQuery.ajax/
You could use [FromBody] attribute in your action method, it specifies that a parameter or property should be bound using the request body.
[HttpPost]
public ActionResult SomeReport([FromBody] string input)
{
var model = new ReportBL();
var report = model.Process(input);
return View(report);
}

MVC3 Controller not receiving any parameter values

Using JQuery, I am passing values to an action in the controller. customerId and productId are not null:
$.ajax({
type: "GET",
url: "Customer/Product/",
data: { Customer: customerID, Product: productId},
dataType: "json",
error: function (xhr, status, error) {
// you may need to handle me if the json is invalid
// this is the ajax object
},
success: function (json) {
$("#productName").innerHTML = json;
alert(json);
alert($("#startDate").innerHTML);
}
});
In MVC3 controller, i have the action:
public ActionResult Product(string Customer, string Product)
{
//both are null
}
I don't know why both are null? Please guide
$.ajax({
type: "GET",
url: "Customer/Product/",
data: "Customer="+customerID +"&Product="+productId,
dataType: "json",
error: function (xhr, status, error) {
// you may need to handle me if the json is invalid
// this is the ajax object
},
success: function (json) {
$("#productName").innerHTML = json;
alert(json);
alert($("#startDate").innerHTML);
}
});
Try this way.
MVC may be expecting a JSON string. Try using this as your data
data: JSON.stringify({ Customer: customerID, Product: productId})
If you change it to a "POST" request it should work.
However it looks like you are actually trying to just "GET" data from the server which should really be encoded in your URL e.g. mysite.com/Customer/{customer_id}/Product/{product_id}. In this case you'll probably need to change your routing rules.
I just did "File -> New Project" and just added the one controller and tried directly using:
var customerID = 42;
var productId = 4242;
$.ajax({
type: "GET",
url: "http://localhost:51622/Customer/Product",
data: { Customer: customerID, Product: productId},
dataType: "json",
error: function (xhr, status, error) {
// you may need to handle me if the json is invalid
// this is the ajax object
},
success: function (json) {
console.log(json);
}
});
It binds the values just fine, so you might want to grab fiddler or something similiar and make sure that you are actually sending values to the server.

Categories