I need to submit a simple form and validate the model. If the model is valid, I would like to serialize that model and send it via POST to an external (https) web service using custom headers. Finally I would handle the response that I get back from the request and display the appropriate message.
I am validating the model from the controller perfectly and serialize the object but can't seem to find a way to create a JSON post request to the external URI. Is there a way to do this using JQuery.ajax or $.post. Maybe I am missing a key ajax param to achieve this.
Thanks
So based on the clarification on the question this is what you can do:
Define the controller method that will validate the object
public ActionResult TestMethod() {
// do server-side validation
return Json(aValidObject);
}
You do an ajax post to your controller so you can validate your model then get back a json result.
$.ajax({
url: '#Url.Action("TestMethod")',
data: some_data,
type: "post",
success: function (result) {
// result is a valid json object
doExternalPost(result);
}
});
Add custom header and do the external post
function doExternalPost(o) {
$.ajax({
url: 'http://some_external_url',
data: o,
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader('custom_header', 'some_value');
},
success: function() {
// post is sucessful
},
error: function (xhr, errorType, exception) {
var errorMessage = exception || xhr.statusText || xhr.responseText;
alert('An error has occured: ' + errorMessage);
},
});
}
try this
var data = {jsonDataObjectHere};
var request = $.ajax({
url : 'externalUrl.com/something.whatever',
type : 'POST',
data : data // see above
});
request.success(function(response){
// the response is the stuff from the server
});
i'm sleepy so forgive typos
good luck
EDIT: for a bit of clarification, with MVC you really dont need to serialize the json object, mvc will accept it as it is.
Related
I'm having trouble extracting data from an AJAX request in ASP.NET Core Razor Pages.
Ajax Request Code (contained in a <script> block on a razor pages .cshtml page:
$("body").ready(function AjaxTest() {
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'text',
url: '/Menus/Admin_MainMenu?action=TestMethod',
method: 'GET',
success: function (data) {
alert("Request Successful" + data);
},
error: function () {
alert("Request Failed");
}
});
})
And the corresponding PageModel method (just as test at the moment):
[HttpGet]
public string TestMethod()
{
string mystring = "success";
return mystring;
}
I know the request works, as I get the alert "Request Successful". However, instead of "Request Successful" being followed by my value of mystring, I get a string of HTML corresponding to the layout of the .cshtml page.
I've tried changing the data type to JSON (both in the AJAX request using dataType, and in the method return type (jsonrequest), but that makes the request fail.
Any help is greatly appreciated. Thanks.
The problem when using dataType: 'text' is that the string may rendered as HTML output instead of simple string. Also declaring function AjaxTest() inside ready event is not a proper way to declare function inside AJAX callback, even the syntax is valid because of scoping issue.
You need to use JsonResult return type instead of string:
public JsonResult OnGetTestMethod()
{
string mystring = "success";
return new JsonResult(mystring);
}
Then use handler parameter inside AJAX call:
$(document).ready(function () {
$.ajax({
dataType: 'json',
url: '/Menus/Admin_MainMenu?handler=TestMethod',
type: 'GET',
success: function (data) {
alert("Request Successful " + data);
},
error: function () {
alert("Request Failed");
}
});
});
Note:
1) The JsonResult mentioned here is not System.Web.Mvc.JsonResult, it uses Microsoft.AspNetCore.Mvc.JsonResult and doesn't have JsonRequestBehavior property.
2) Razor pages uses OnGet and OnPost action method prefixes to deal with HTTP GET and POST respectively, hence the [HttpGet] attribute is unnecessary.
Further references:
Handle Ajax Requests in ASP.NET Core Razor Pages
ASP.NET Core Razor Pages: How to implement AJAX requests
Why we are unable to access TempData during ajax request.
Controller:
TempData["MytempData"] = MyMessage;
return Json(true, JsonRequestBehavior.AllowGet)
View:
$.ajax(
{
type: 'POST',
success: function (result) {
value=TempData["MytempData"];//why this is not possible
},
});
Also I know that i can access this data using json object ,as following
return Json(new {isSucess=true,Message=MyMessage},JsonRequestBehavior.AllowGet)
but my question is not about how should i pass data from controller to view.I just want to know the reason that why we are unable to access the TempData during ajax request.
The razor compiler will view value=TempData["MytempData"] as javascript and will not try to compile it as C#. To tell razor that it is C# you need to prepend #
$.ajax(
{
type: 'POST',
success: function (result) {
value=#TempData["MytempData"];//Should work now.
},
});
but bear in mind that will be of type object so you may wish to cast it as well.
I am passing json data to my generic handler page GenericHandler.ashx.cs using jquery ajax request and json as data type.
in my handler code i would like to return html table in string format. here is snap of my handler code
context.Response.ContentType = "text/plain";
context.Response.Write(sResponse);
where sResponse contains <table><tr><td>PropertyName</td><td>PropertyID</td></tr><tr><td>abc</td><td>1</td></tr></table>
my jquery code (check inline comment in error function):
id = { 'PropertyID': id };
$.ajax("Handlers/GenericHandler.ashx?Type=getProperties",
{
type: 'post',
dataType: 'json',
cache: false,
contentType: "application/json",
data: JSON.stringify(id),
success: function (data) {
console.log(data);
},
error: function (xhr, status) {
console.log(status); // Output as parseError
console.log(xhr.responseText); // My sResponse string ! But Why Here ?
}
});
My Question :
Why i am not getting response in success function
Is it right way to do ? or should i convert html table to json object and then return it. And again display it in tabular format ?
From jQuery documentation here, you can see that the dataType parameter is what AJAX is expecting back as a response from the server. The contentType parameter is what is put in the header in your request to the server so that the server knows how to read the request.
Therefore, you should change your dataType to "text" like:
$.ajax("Handlers/GenericHandler.ashx?Type=getProperties",
{
type: 'post',
cache: false,
dataType: 'text',
contentType: "application/json",
data: JSON.stringify(id),
success: function (data) {
console.log(data);
},
error: function (xhr, status) {
console.log(status);
console.log(xhr.responseText);
}
});
I find this useful when alerting of a successful INSERT or UPDATE call on a database. It would be extraneous to create and return a JSON object for such a task.
Your response isn't valid JSON sine it's returning plain text. jQuery is expecting the response to be JSON because you've set contentType: "application/json"
If the rest of your site uses JSON as a transmission format, then wrap your HTML as a JSON object and return it.
In your back end code, return something that looks like this
{response_html : "<table><tr><td>PropertyName</td><td>PropertyID</td></tr><tr><td>abc</td><td>1</td></tr></table>"}
And in your jQUery code, you can access it in the success callback.
success: function (data) {
console.log(data.response_html);
},
NOTE - You'll need to remove the plain text content type from your backend code and make that JSON.
If you tell $.ajax that you expect a JSON, then a text/plain response from the server is not a valid response.
Regarding your second question: The good way to do it would be to return the data you want to work with, in JSON format, for example:
[
{ "label" : "PropertyName", "value" : "abc" },
{ "label" : "PropertyId", "value" : "1" }
]
And then in the success callback of your Ajax request, work with that data to build your HTML structure with jQuery.
I want to send a JSON object and values from text boxes back to my controller, but I am having trouble. I can send just the JSON object successfully, but as soon as I add other parameters I get an error saying the requested resource does not support http method 'PUT'. I have tried commenting out the contentType and using Data: {viewModel: JSON.stringify(jsonData), userName: username}, without any success (I eventually will add more string parameters). Below is my ajax and controller signature. Thanks in advance.
$.ajax({
type: 'PUT',
contentType: 'application/json',
url: 'api/Label',
cache: false,
data: JSON.stringify(jsonData),
success: function (result) {
// TODO
},
error: function (HttpRequest, textStatus, err) {
var response = jQuery.parseJSON(HttpRequest.responseText);
$('#LabelInfo').show();
$('#LabelInfo').text('Error: ' + response.ModelState["viewModel.Pieces"][0]);
}
});
controller signature:
public HttpResponseMessage Put(Label viewModel, string
userName)
this is my function, where i post json only
function test() {
var imgFile = document.getElementById('image');
// var imgData = JSON.stringify(getBase64Image(imgElem));
//var imgData = Convert.FormBase64String(imgElem);
$.ajax({
type: 'POST',
dataType: 'json',
url: "http://localhost:59102/Contacts/AddContact",
data: "json=" + "{\"token\":\"8mVm/nS1OfpU+nlQLbJjqXJ7kJI=VyLGI2GEKkGgtDt0babrAw==\"}",
success: function (returnPayload) {
console && console.log("request succeeded");
},
error: function (xhr, ajaxOptions, thrownError) {
console && console.log("request failed");
},
processData: false,
async: false
});
and i dont know how to add to my data, image, i need to post json and image
this is my controller
[HttpPost]
[AllowAnonymous]
public JsonResult AddContact(string json, HttpPostedFileBase file)
{}
You can't upload files via AJAX (by design) unless you use a plugin that utilises other 'technology' such as flash, or iframes - this is a security measure as JavaScript reading local files on your machine would not be the best idea
There's an option here: http://jquery.malsup.com/form/
...otherwise I suggest looking up one of the many other alternatives!
after you getting the data to a base 64 , your json should be an object
from your controller your json should be something like this
{"json":"something here that is a string","file":"some file"}
Also on the client side you should have a n object on which you invoke JSON.stringify()
var ob = {json:imageDataAsBase64,file:fileDataAsBinary}
although I dont see the reason to send both.
if what you need is just transafering an image that you just need to get the image as base64 and post it as a json