Post a string to mvc - c#

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);
}

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 request to razor page using handler

I am trying to get data from Active.cshtml.cs file using ajax call.
Here is the jquery code:
var turl = '/Active?handler=Clients/' + id;
$.ajax({
type: "GET",
url: turl,
dataType: "json",
success: function (result) {
alert(JSON.stringify(result));
});
Here is Active.cshtml.cs method
public JsonResult OnGetClients()
{
return new JsonResult("new result");
}
The status is 200 Ok, but it shows the entire webpage in response. Ideally it should return "new result" in Network tab of developer tools. Is it that I have Active.cshtml and Active.cshtml.cs in Pages that creates the confusion? How can I resolve it?
Thanks
For razor pages, you should be passing the parameter value(s) for your handler method in querystring.
This should work.
yourSiteBaseUrl/Index?handler=Clients&53
Assuming your OnGetClients has an id parameter.
public JsonResult OnGetClients(int id)
{
return new JsonResult("new result:"+id);
}
So your ajax code should look something like this
var id = 53;
var turl = '/Index?handler=Clients&id=' + id;
$.ajax({
type: "GET",
url: turl,
success: function (result) {
console.log(result);
}
});

.NET (ApiController) / jQuery .ajax : what to return from POST?

In a Post method within a Controller derived from ApiController what should I return to indicate success to jQuery ?
I've tried HttpResponseMessage but jQuery sees this as an error (even though the argument the jQuery error handler clearly has a 200 status).
The jQuery looks like this :
processParticipantEvent: function(parID, evtType, evtNotes, successFunction, errorFunction){
debugger;
var requestURL = '/api/participantevent';
var json = {"parId" : parID, "evtType": evtType, "evtNotes": evtNotes};
var jsonArray=JSON.stringify(json);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: requestURL,
data: jsonArray ,
dataType: "json",
success: function (data) { successFunction(data); },
error: function (data) { errorFunction(data); }
});
},
I've read this : Ajax request returns 200 OK, but an error event is fired instead of success which seems like it's touching on the same issue but I suspect it's out of data as it won't work for me ?
Just to be clear all I want to do is to return a plain old 2xx with no data.
As per the documentation:
"json": Evaluates the response as JSON and returns a JavaScript
object. Cross-domain "json" requests are converted to "jsonp" unless
the request includes jsonp: false in its request options. The JSON
data is parsed in a strict manner; any malformed JSON is rejected and
a parse error is thrown. As of jQuery 1.9, an empty response is also
rejected; the server should return a response of null or {} instead.
So if you want to use jQuery ajax you have to return a valid json string, just use the following in your API controller:
return Ok(new {});
Note this is a jQuery ajax "feature", using Angular for example to do an ajax post I can use return Ok(); inside my controller and everything works as expected.
As mentioned by #Beyers the return with OK() just works.
I've created the same structure here and worked.
My Controller has this:
[Route("api/participantevent")]
public IHttpActionResult Test()
{
return Ok("");
}
And at client I've changed your function just to simplify:
processParticipantEvent= function(){
debugger;
var requestURL = '/api/participantevent';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: requestURL,
data: [{'test': '1'}] ,
dataType: "json",
success: function (data) { alert('success'); },
error: function (data) { alert('error'); }
});
}
Your error is with the requestURL. Its value is absolute and http://api/participantevent does not exist. Try using a relative value.
var requestURL = './api/participantevent';
It seems that if you get an OK response, It is probably not a valid JSON.
I would recommend to you to check the HTTP response in the browser and try to run the JSON.parse function with the responseText and see whether it fails.
I usually declare a class like below:
public class AjaxResult
{
private bool success = true;
private List<string> messages;
public bool Success { get { return success; } set { success = value; } }
public List<string> Messages { get { return messages; } }
public AjaxResult()
{
messages = new List<string>();
}
}
In the controller, the action(to which the ajax request is made) should have JsonResult as return type.
[HttpPost]
public JsonResult Action(string id)
{
AjaxResult result = new AjaxResult();
//Set the properties of result here...
result.Success = true;
result.messages.Add("Success");
return Json(result);
}
3.And your ajax call will look like this:
$.ajax({
type: "POST",
dataType: 'json',
url: /ControllerName/Action,
data: { id: "Test"},
success: function (data) { alert('success'); },
error: function (data) { alert('error'); }
});

Passing JSON to WebApi in MVC5

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.

Sending csv through Ajax

I'm trying to senda csv file opened with JS to the method written in C# where csv file will be parsed and added to database.
I have no problem with opening file and getting its contents.
But whatever I do with my Ajax call I receive empty data in the method CreateFromFile.
here you can see my code:
var a = fr.result;
$.ajax({
url: "/DeviceInstance/CreateFromFile",
type: "POST",
datatype: "html",
data: a,
error: function (data) {
alert("Dodanie nie powiodło się Jeden lub wiecej numerów seryjnych nie są nikalne " + data);
},
success: function (data) {
if (data.length > 0) {
alert(data);
}
else {
alert("Operacja zakonczona sukcesem")
}
}
});
and:
[HttpPost]
public JsonResult CreateFromFile(object data)
{
return Json("Sukces");
}
I'm asking how should i modify my code to make things work?
here : fr.result:
samsung;galaxy ;s3;1234567
samsung;galaxy ;s4;54321
samsung;galaxy ;s5;34567yu8
You could read the request input stream to access the body payload:
[HttpPost]
public JsonResult CreateFromFile()
{
byte[] data = new byte[Request.InputStream.Length];
Request.InputStream.Read(data, 0, data.Length);
string csv = Encoding.UTF8.GetString(data);
// ... do something with the csv
return Json("Sukces");
}
Also in your AJAX request you seem to have specified datatype: "html". There are 2 problems with this:
The parameter is called dataType instead of datatype.
You specified html but your controller action returns JSON.
So that's very inconsistent thing. I would recommend you to get rid of this parameter and leave jQuery use the response Content-Type header to automatically infer the correct type.
Try the following (assuming your a payload is really a string):
$.ajax({
url: '/DeviceInstance/CreateFromFile',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({ dane: a }),
/* callbacks */
});
And your controller action should now look like the following:
[HttpPost]
public JsonResult CreateFromFile(string dane)
{
// Parse CSV data from "dane"
}
Hope this helps.

Categories