MVC - Pass value to controller via JS - javascript

I have a drop down
<%=Html.DropDownList("genre", Model.genres, "", new { #onchange = ChangeMovie()" })%>
The JavaScript looks like (incomplete)
function ChangeMovie() {
var genreSelection = container.find( '#genre' ).val();
$.ajax({
"url" : "/Movies/GetGenre" ,
"type" : "get" ,
"dataType" : "json" ,
"data" : { "selectedValue" : $( "#genre").val() },
"success" : function (data) {}
});
};
Conrtroller code
public ActionResult GetGenre(string genreName)
{
//Need to get the `genreName` from the JavaScript function above.. which is
// in turn coming from the selected value of the drop down in the beginning.
}
I want to pass the selected value of the drop down to the action result in the controller code via the js function. I need help manipulating the JavaScript code and the AJAX call code so the correct value is passed onto the controller.

You have a lot of unnecessary quotes as well not returning JSON in your action
$.ajax({
url: "/Movies/GetGenre/",
dataType: "json",
cache: false,
type: 'GET',
data: {genreName: $("#genre").val() },
success: function (result) {
if(result.Success) {
alert(result.Genre);
}
}
});
Plus your controller isn't returning Json, modify your action to this
public JsonResult GetGenre(string genreName) {
// do what you need to with genreName here
return Json(new { Success = true, Genre = genreName }, JsonRequestBehavior.AllowGet);
}

For model binding to function correctly, field names of passed json object should match parameter names of your controller action. So, this should work
"data" : { "genreName" : $( "#genre").val() },

The parameter name of the value you're posting in the Ajax request does not match the Action parameter name. selectedValue should be genreName.
Change this:
"data" : { "selectedValue" : $( "#genre").val() },
to this:
data : { genreName : $("#genre").val() },

Related

how to change the code from $.ajax() to $.getJSON

this code works using ajax and I want to change it using json, what is the right way to use it?
AJAX
$('#movie-list').on('click', '.see-detail', function() {
$.ajax({
url: 'http://omdbapi.com',
dataType: 'json',
data: {
'apikey' : 'myapikey',
'i' : $(this).data('id')
},
success: function (movie) {
$('.modal-body').html(`...`);
}
})
});
JSON
$('#movie-list').on('click', '.see-detail', function() {
$.getJSON('http://www.omdbapi.com/?apikey=myapikey&i=='+ $(this).data('id') +'', function(data) {
$('.modal-body').html(`...`);
});
});
Look at the documentation:
jQuery.getJSON( url [, data ] [, success ] )
So:
jQuery.getJSON(
'http://omdbapi.com', // url
{ // data
'apikey' : 'myapikey',
'i' : $(this).data('id')
},
function (movie) { // success
$('.modal-body').html(`...`);
}
);
While you could munge the query string on to the URL by mashing strings together: Don't. We use libraries to do it because they are less error prone and know all the rules for properly escaping data.

How do I bind object property and send the data via ajax?

I'm struggling with sending a data which contains object as a member property.
This is the domain class.
public class Timeline extends Post{
String picture;
User user;
int like;
...
(getters and setters)
}
And I've got the JSON data with this code already so I could get the data from 'obj' variable.
var obj;
$.ajax({
method: "GET",
dataType: "json",
url: serverRoot + "/json/auth/loginUser",
async: false
})
.done(function(data) {
obj = data;
});
And the returned data looks like this.
"user" : {
"userNo" : 1,
"name" : "user01",
...
}
The next JSON data is the data I'd like to send to a server.
{
"no" : 23,
"content" : "hihi",
"createdData" : "2018-07-22",
"picture" : null,
"user" : {
"userNo" : 1,
"name" : "user01",
... **obj JSON data I got above**
}
}
And this is the codes to send to a server.
(Here is the thing I've been stuck)
$("#sh-tl-post-btn").click(() => {
$.ajax({
type: 'POST',
url: '../../../json/timeline/add',
data: {
picture: $('#sh_tl_upload').val(),
content: $('#sh_tl_post_write').val(),
**user: [{"userNo":obj.userNo}]**
},
}).done(function() {
console.log("inserted.");
location.href = "timeline.html"
});
});
The Mapper file looks like this.
<insert id="insert" parameterType="Timeline">
<choose>
<when test="picture != ''">
insert into TML(tmlno, uno, tmlpath)
values(#{no}, #{userNo}, #{picture})
</when>
<otherwise>
insert into TML(tmlno, uno)
values(#{no}, #{userNo})
</otherwise>
</choose>
</insert>
I've been searching what to write on here instead of
user: [{"userNo":obj.userNo}] , this...
I've been trying
user : {"userNo" : obj.userNo}
user.userNo : obj.userNo
user.[0].userNo : obj.userNo
...
but the console keeps saying
[Request processing failed; nested exception is
org.springframework.beans.InvalidPropertyException:.....
this kind of errors.
Is there anyone could help me how to bind the nested object's property via ajax
JSON data? Thanks in advance.

MVC 5 generate form data with AJAX

I need a way to generate a new unique id for a user when a person focuses out of a textbox. I am using MVC 5 for this application. Here is my controller, everything in the controller has been unit tested and it does return the string value that I need.
Controller. I was able to visit that URL, and I did download a JSON file with the correct data.
public ActionResult GetNewId()
{
string newId = utils.newEmployeeId();
return Json(new {eId = newId}, JsonRequestBehavior.AllowGet);
}
Javascript, JQuery call to that controller. I do not know how to properly reference the ActionResult. I keep getting undefined errors on eId.
$(function () {
$('#employeeId').focusout(function () {
if($("#employeeId").val() === "NP")
$.ajax({
type: 'GET',
url: '#Html.ActionLink("GetNewId", "Employees")',
data: { 'eId': eId },
dataType: 'json',
success: function (response) {
$("#employeeId").val(eId);
},
error: function (response) {
alert(response);
}
});
});
});
The problem is with yout ajax request:
1.you need to change the url in the reuqest but it like this
{{yourcontroller}/GetNewId}
2.remove the "data: { 'eId': eId }" you dont need it, youre not posting anything to the server.
change your $("#employeeId").val(eId); to
$("#employeeId").val(response.eId);
this will 100% work

Pass an array as parameter to a controller from an ajax call in JavaScript

I'm working on an ASP.NET MVC 4 website and I've got some troubles with a functionality. I explain, I've to select entities displayed in a table with their linked checkbox :
Screenshot of my table where each row has a checkbox with the same Id as the entity
Console showing updates in the array
Inside my script I have been abled to store each checked Id's checkbox in an array and remove those if the checkbox is unchecked. But I can't pass the array to my controller's function to delete each selected entity in the database.
I used $.ajax() from jquery to send through a POST request the array (as JSON) but I always get 500 error :
JSON primitive invalid
Null reference
Here's my function in my script (I don't know if my array's format is valid) :
var sendDocsToDelete = function (docsArray) {
$.ajax({
type: 'POST',
url: 'Main/DeleteDocuments',
data: JSON.stringify(docsArray),
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
alert('Success ' + result.d);
},
error: function (result) {
alert('Fail ' + result.d);
}
});
}
Then, the POST call the following function in my controller :
[Authorize]
[WebMethod]
public void DeleteDocuments(string docsToDelete)
{
int id;
string[] arrayDocs = JsonConvert.DeserializeObject<string[]>(docsToDelete);
foreach (string docId in arrayDocs)
{
int.TryParse(docId, out id);
dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
}
Update 2
[Authorize]
public ActionResult DeleteDocuments(int[] docsToDelete)
{
try{
foreach (string docId in arrayDocs)
{
int.TryParse(docId, out id);
dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
return Json("Success");
}
catch
{
return Json("Error");
}
}
var sendDocsToDelete = function (docsArray) {
$.ajax({
type: 'POST',
url: 'Main/DeleteDocuments',
data: docsArray,
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
alert('Success ' + result.d);
},
error: function (result) {
alert('Fail ' + result.d);
}
});
}
Any ideas about this issue ? I hoped I was clear enough. Do not hesitate if you need more details.
If you are passing an integer array properly from $.ajax (i.e. your docsArray should be having value like [15,18,25,30,42,49]) then you should try :
[Authorize]
public ActionResult DeleteDocuments(int[] docsArray)
{
//int id;
//string[] arrayDocs = JsonConvert.DeserializeObject<string[]>(docsToDelete);
try {
foreach (int docId in docsArray)
{
//int.TryParse(docId, out id);
dal.DeleteDocument(docId); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
return "Success ";
}
catch {
return "Error";
}
}
Update :
Your javascript code should be :
var sendDocsToDelete = function (docsArray) {
$.ajax({
type: 'POST',
url: 'Main/DeleteDocuments',
data: JSON.stringify(docsArray),
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
alert('Success ');
},
error: function (result) {
alert('Fail ');
}
});
}
Maybe the datatype in the JSON array is not a string? (This could happen if you have an array in the form of [45,64,34,6], or a mixed one like [345,"wef4"]).
To make sure something is a string in Javascript you can do this: var string = "".concat(otherVar);
Try changing your ajax data to something like this..
data : JSON.stringify({'docsToDelete':docsArray}),
Make these changes to your code.
In Jquery
data: docsArray, no need to stringify the array
In Controller
[Authorize] //remove [WebMethod]
public ActionResult DeleteDocuments(string[] docsToDelete) //Add ActionResult, Change parameter to accept array
{
int id;
string[] arrayDocs = docsToDelete; //no need of deserilization
foreach (string docId in arrayDocs)
{
int.TryParse(docId, out id);
dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
return Json(id); //return id back to ajax call...
}

jquery -ajax not check the boolean value from controller

i have a controller action which is return a boolean result to the jquery.
[HttpGet]
public ActionResult IsVoucherValid(string voucherCode)
{
bool result = false;
var voucher = new VoucherCode(voucherCode);
if(voucher.Status==0)
{
result = true;
}
return Json(result);
}
and call this controller using ajax code
$.ajax({
url: '/Account/IsVoucherValid?voucherCode=' + code,
type: 'Get',
contentType: 'application/json;',
success: function (data) {
alert("success");
if (data) {
//if result=true, want to work this
$("#person-data").css({ "display": "block" });
}
},
error:alert("error")
});
in the success of ajax the json result is true then want to work the css. but this is not working please help me.
result is a variable name that only exists in that action method. It will not be included in the JSON.
I'm pretty sure that your boolean value will be stored in data since you are only sending back a single value:
$.ajax({
url: '/Account/IsVoucherValid?voucherCode=' + code,
type: 'Get',
contentType: 'application/json;',
success: function (data) {
if (data) { //if result=true, want to work this
$("#person-data").css({ "display": "block" });
}
}
});
If in doubt, do console.log(data) to see what it contains. You should at least be doing minimal debugging before you bring the question to us.
Also, as #Stephen Muecke points out below, if you are retrieving this data with GET, you need to use:
return Json(result, JsonRequestBehavior.AllowGet);

Categories