In my web api project, I got a controller named ContactController and a method named Synchro in it which waits for a list of string as below:
[HttpPost]
[Route("api/Contact/Synchro")]
public IHttpActionResult Synchro([FromBody]List<string> listNumTel)
{
List<Profil> listContact = new List<Profil>();
if (listNumTel.Count() > 0)
{
try
{
listContact = Librairie.Contacts.getContactSync(listNumTel);
return Ok(listContact);
}
catch(Exception e) {
return InternalServerError(e);
}
}
else
{
return BadRequest();
}
}
To test that method, I've created the ajax called below:
$("#btn_synchro").click(function () {
$.ajax({
url: '../api/Contact/Synchro',
type: 'POST',
data: {
"listNumTel": [
"+33640512999",
"+33640522997",
"+33640182998",
"+33640742996"]
},
dataType: 'json',
success: function (data) {
alert('Synchro réussi: ' + data);
},
error: function (request, error) {
alert("Erreur lors de la synchro");
}
})
});
When I test on debug mode, the call works fine but the method get a null list. I checked if the json is valid and it is. Does Somebody sees what could be wrong ? Thanks in advance !
Thanks for the answers, but I've just found out the solution. It was all about JSON sent. To send a list of string by an ajax call for example, the JSON should looks like below the variable listNumero
("#btn_synchro").click(function () {
var listNumero =
[ '+33640532999',
'+33640532997',
'+33640532998',
'+33640532996'];
$.ajax({
url: '../api/Contact/Synchro',
type: 'POST',
data: JSON.stringify(listNumero),
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('Synchro réussi: ' + data);
},
error: function (request, error) {
alert("Erreur lors de la synchro");
}
})
});
You can compare to my post, the JSON is different. Now my web api controller can get the values from the list.
Related
I want to perform an Ajax Call to get data from a form that is in a partial view, to a controller and get a response message back.
Ajax Call
$("#submitContactInfo").on("click", function () {
if ($('#contact-form').valid() === true) {
$.ajax({
url: '#Url.Action("SendEmailAsync", "Home")',
type: "Post",
data: {
"name": Name.value,
"lastName": LastName.value,
"email": Mail.value,
"phone": Mobile.value
},
dataType: "json",
success: function (result) {
if (result.value === "1") {
...
}
else {
...
}
}
});
}
});
My Controller
[HttpPost]
public async System.Threading.Tasks.Task<ActionResult> SendEmailAsync(string name, string lastname, string email, string phone)
{
var value = 0;
...
return Json(value, JsonRequestBehavior.AllowGet);
}
First thing I stumbled upon was that#Scripts{} does not work on partial views so I had to think of another way.
So I created an external file and named it 'custom.js' and referenced it on _Layout.chtml, below the:
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
...
#Scripts.Render("~/Scripts/custom.js")
The second thing I noticed was that the url from the Ajax Call was not working because I was using Razor syntax in an external js file.
So I changed url: '#Url.Action("SendEmailAsync", "Home")', to url: '/Home/SendEmailAsync',
After that I was getting a 500 error, so I figured that by changing type: "Post", to type: "Get", and dataType: "json", to dataType: "html", and by adding contentType: "application/json; charset=utf-8", I was a little closer because I was getting a 404 error.
So I went to my Controller method and removed [HTTPPOST] and that was it.
Final Ajax Call:
$("#submitContactInfo").on("click", function () {
if ($('#contact-form').valid() === true) {
$.ajax({
url: '/Home/SendEmailAsync',
type: "GET",
data: {
"name": Name.value,
"lastName": LastName.value,
"email": Mail.value,
"phone": Mobile.value
},
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (result) {
if (result === "1") {
...
}
else {
...
}
}
});
}
});
My Controller
public async System.Threading.Tasks.Task<ActionResult> SendEmailAsync(string name, string lastname, string email, string phone)
{
var value = 0;
...
return Json(value, JsonRequestBehavior.AllowGet);
}
If you have a better solution or any remarks to make, feel free. I'm open to suggestions.
I have a select box in my view.an ajax request is passed through its change.But found an 302 error.My code is below.It doesn't hit to the controller action.In network header status code is 302 found shown.Why this error occur and how to solve this. Here is code:
$(document).on('change', '.memberType', function () {
var memberTypeID = $(".memberType").val();
if (memberTypeID != null) {
alert(memberTypeID)
$.ajax({
type: "POST",
url: "#Url.Action("GetDetailsMember", "Approvemembership")",
data: JSON.stringify({ memberTypeIDJson: memberTypeID }),
contentType: "application/json; charset=utf-8",
success: function (data) {
data = JSON.parse(data)
if (data.IsStaff ){
$('.staffDetail').show();
$('.studentDetail').hide();
}
else if (data.IsStudent) {
$('.studentDetail').show();
$('.staffDetail').hide();
}
else {
$('.staffDetail').hide();
$('.studentDetail').hide();
}
}
});
}
})
public string GetDetailsMember(string memberTypeIDJson)
{
SchooberrySchoolEntities db=new SchooberrySchoolEntities();
var memberType = db.LibraryMemberTypes.Where(p => p.MemberTypeId == memberTypeIDJson).Select(p =>new{IsStudent=p.IsStudent,IsStaff=p.IsStaff}).FirstOrDefault();
if (memberType != null)
{
return JsonConvert.SerializeObject(memberType);
}
else
{
return "false";
}
}
Change your url url: "#Url.Action("GetDetailsMember", "Approvemembership")", to url: "/Approvemembership/GetDetailsMember" it will work.
Please check this answer AJAX POST to MVC Controller showing 302 error
I have a controller which return a model as json object:
[HttpGet("{id}")]
[Route("GetById")]
public async Task <JsonResult> GetById([FromQuery]string id)
{
var myfoo = new {foo="bar", baz="Blech"};
return Json(myfoo);
}
How can handle the returned json object in jQuery?
<script type="text/javascript">
$('#id').change(function () {
var id = $('#id').val();
if (id.length = 17) {
$.ajax(
{
url: '/Home/GetById?id=' + id,
type: 'GET',
jsondata: "",
contentType: 'application/json; charset=utf-8',
success: function (jsondata) {
alert("foo is: " + jsondata ); <---?
},
error: function () {
//alert("error");
}
});
}
});
</script>
I need to get foo value and assigned to an html control
Thanks in advance
all the time I was using capital letter
jsondata.foo // not .Foo
I'm new in DNN development.
I have created a very simple module in Visual studio--- A textbox and a button.
I just want to call the action in a controller by click the button, then show the return result in the textbox.
The code call the action success, but not sure why append lots of HTML inforation in the result.
Here is the action in the controller:
public ActionResult test1()
{
return Content("Return something");
}
Here is the Ajax code from the View:
$(document).ready(function () {
$("#btnSub").click(function () {
//alert(this.action);
$.ajax({
type:"GET",
contentType:"application/text",
url: "#Url.Action("test1", "Sky")",
data:"",
dataType: "text",
success: function (data) { $("#txtResult").val(data); alert("Success!") },
error:function(){alert("Failed!")}
});
});
});
And here is the result show in the textbox:
Anyone can let me know why the HTML information returned? Actually, I don't need it.
Thanks
Unfortunately, as described in DNN8 MVC unsupported features, it's not yet possible to return a JsonResult. So the solution I used is to return an ActionResult (although the function returns Json):
public ActionResult Test()
{
return Json(new { success = true });
}
On jquery side, I setup ajax call to receive result as html. This avoid the browser to display a parsing error. Finally, just need to remove the html part and manually parse the response. It's not very clean, but the only solution I found until DNN support JsonResult.
$.ajax({
url: '#Url.Action("Index", "Contact")',
type: 'POST',
dataType: 'html',
data: $('#contact-form input').serialize(),
success: function (response) {
jsonPart = response.substring(0, response.indexOf("<!DOCTYPE html>"));
var data = JSON.parse(jsonPart);
if (data.success) {
alert("Great");
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error!");
}
});
EDIT : Improved solution
DNN8 now support IMvcRouteMapper. You can then register a route in RouteConfig.cs. Once done, you can call the function using following URL :
/DesktopModules/MVC/ModuleName/Controller/Action
The action can return a JsonResult. But pay attention, if you just call that function, it will fail with a null exception on ModuleContext. You have to include in the ajax call the following header :
headers: {
"ModuleId": #Dnn.ModuleContext.ModuleId,
"TabId": #Dnn.ModuleContext.TabId,
"RequestVerificationToken": $("input[name='__RequestVerificationToken']").val()
}
You can find the module complete code here.
This is a working ajax call in DNN 9. You dont have to use #urlaction it will give whole html as well as data. dnn.getVar("sf_siteRoot", "/") +
"DesktopModules/MVC/ModuleName/Controller/Action", this does the trick and don't forget to add the header otherwise it will throw 500 error.
$.ajax({
url: dnn.getVar("sf_siteRoot", "/") +
"DesktopModules/MVC/ModuleName/Controller/Action",
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: "{ 'id':" + JSON.stringify(3543)+" }",
headers: {
"ModuleId": #Dnn.ModuleContext.ModuleId,
"TabId": #Dnn.ModuleCon`enter code here`text.TabId,
"RequestVerificationToken":
$("input[name='__RequestVerificationToken']").val()
},
success: function (response) {
debugger;
},
error: function (errmsg) {
alert("Error!");
}
});
Your controller should be
[HttpPost]
public ActionResult ActionName(int id)
{
var data = id;
return BuidJsonResult(true,data);
}
Happy Coding :)
I am unable to get my JSON to my controller, and I can't figure out why the value I get in javascript isn't being passed to the controller. Here is my ajax post in my javascript:
this.save = function () {
var data = ko.toJSON(this.Routines);
$.ajax({
type: 'POST',
url: "CreateJson",
data: data,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
if (!result.success)
alert("test")
else { }
}
})
}
now data contains
[{"routine_name":"new routine","duration":"20","rest":"10","rounds":1}]
which is what I want, but the controller shows nothing. Here is my controller
[HttpPost]
public JsonResult CreateJson(t_routine routine, string data)
{
var message = "success";
return Json(message);
}
As I understand it, MVC 3+ automatically receives JSON without any need for parameters like my string data, I just threw it in there to try and figure out if I'm getting anything at all. data is null and routine shows 0's and null for values. What am I missing?
If t_routine represents the server side type for
[{"routine_name":"new routine","duration":"20","rest":"10","rounds":1}]
Then it might be enough to call JSON.stringify on the ko.toJSON result like this
this.save = function () {
var data = JSON.stringify(ko.toJSON(this.Routines));
$.ajax({
type: 'POST',
url: "CreateJson",
data: data,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
if (!result.success)
alert("test")
else { }
}
})
}
the data parameter on your controller action is not needed then and you most likely need to change the t_routine parameter to t_routine[]