How to pass multiple arguments to MVC Action through Ajax Function? - ajax

I am trying to pass two values to MVC controller as an argument.I know how to pass one but not sure about two.

In #Url.Action("Action_Name","Controller_Name") , you have provided only one of the parameter and in data part please make sure that parameter1 and parameter2 have same name as that of your GetRecord action parameters.

Try something like that:
<script>
$(document).ready(function () {
$("#Verify").click(function () {
var value1 = $('#txtBox1').val();
var value2 = $('#txtBox2').val();
$.ajax({
type: "GET",
url: "#Url.Action("GetRecord")" + "?parameter1=" + value1 + "&parameter2=" + value2,
datatype: "JSON",
success: function (data) {
if (data) {
console.log("Working");
}
}
});
});
});

Related

Parameter shown as "0:" in ajax request

var frm = $('#updateStickyForm');
frm.submit(function (e) {
var id = "{{note.id}}"
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data:
frm.serialize() + '&' + $.param(id),
success: function (data) {
console.log('Submission was successful.');
$('#test').show();
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
});
When I look at the network logs in Chrome the parameter is shown as "0:". I'm able to access the parameter just fine with Django and do what I want to do with it, I just want to know how I can change it from "0" to something of my choosing.
id seems to have a key 0 for the value you want to post, you can construct an object to pass to $.param with the key you want
frm.serialize() + '&' + $.param({"myid":id['0']}),

Model is not passed to controller's action

I have the following code:
<script type="text/javascript">
$('#btnConfirmAddition').click(function () {
var contractorId = $("#contractorId").val();
var contactPerson = $("#addNewContactPersonForm").serialize();
$.ajax({
url: '#Url.Action("AddContactPerson", "Contractors")',
type: "GET",
data: { newContactPerson: contactPerson, contractorId: contractorId },
//data: contactPerson,
success: function (data) {
$("#myModal").modal('hide');
toastr.success("Success");
location.reload();
},
error: function (data) {
$("#errorArea").html(showError(data.ErrorMessage));
toastr.error(data.errorMessage);
}
});
return false;
});
</script>
public JsonResult AddContactPerson(ContactPerson newContactPerson, string contractorId)
{
//Some code
}
When I pass parameters in ajax call as above, my newContactPerson is null and contractorId contains appropriate data.
However when remove contractorId parameter from controller's action and pass parameter in ajax call as follows:
data: contactPerson
it works. I was wondering why? Can someone please help me?
post your data following way,
data: $("#addNewContactPersonForm").serialize() + '&contractorId='+ contractorId
And add data type to Ajax call,
dataType: "json"

How can I load my partial view using ajax call?

I’m trying to load a partial view with an ajax call. I’m trying to follow a solution I found here: Render partial view onclick in asp.net mvc 3 project
My script looks like this:
$("#174").on("click", function () {
$.ajax({
type: "GET",
url: "/TeacherStudent/StudentInformation",
data: "174",
datatype: "html",
sucess: function (data) {
$("#theTimes").html(result);
}
});
});
My controller looks like this:
public ActionResult StudentInformation(string data)
{
int id = Convert.ToInt32(data);
var viewModel = new ScheduleData();
var attend = from s in db.Assignments where s.teacherId == 7 && s.StudentId == 174 select s;
var enroll = from s in db.Enrollments where s.InstructorId == 7 && s.StudentID == 174 select s;
var stdParent = from s in db.Parents select s;
viewModel.Assignments = attend;
viewModel.Enrollments = enroll;
viewModel.Parents = stdParent;
return PartialView("~/Views/Shared/DisplayTemplates/StudentInformation.cshtml");
}
}
Somewhere in my view I have div tag:
<div id="theTimes"></div>
I confirmed that the program calls the partial view but the view does not get displayed in the div tag. What could I be missing in the ajax call? Thanks for helping out!
The problem looks like it's on this line.
sucess: function (data) {
$("#theTimes").html(result);
}
result is undefined and 'sucess' isn't a valid callback.
Try this:
success: function (data) {
$("#theTimes").html(data);
}
Also, change datatype to dataType (grammar) and change data: "174" to data: {"data": "174"}.
I.e.
$("#174").on("click", function () {
$.ajax({
type: "GET",
url: "/TeacherStudent/StudentInformation",
data: {"data": "174"},
dataType: "html",
success: function (data) {
$("#theTimes").html(data);
}
});
});

How to dynamically pass data parameter in a jquery ajax call (multiple arrays of data)

I have this ajax code:
return $.ajax({
type: "POST",
url: "somefile.php",
cache:false,
data: { "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() },
dataType:"json",
success: function(data){
alert("success");
}
This works fine, but I need to pass the data parameter dynamically. For now I need the above data parameter content and a single string.
How do I pass this dynamically? / How do I store it in a variable and pass it to the "data:" field?
{ "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() }
I tried JSON.stringify I I couldn't get it to work probably due to the data being an array.
The year and genre arrays are coming directly from the jquery drop down menu. It is selected like by it's #id like so "$("#yearFilter")". This is the select form element.
<select multiple="multiple" name="yearFilter[]" class="filterChange" id="yearFilter">
What I need at the base level is:
var someData = "";
if(...){
someData = { "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() };
}
else if(...){
someData = "sampleString";
}
And in ajax call:
...
data: someData,
...
I think I have an idea what you want but post has been overly complicated by extraneous issues like json stringify . Here's a function that could be used in several places eleswhere in your code to make one type of AJAX call or another.
You would then perhaps have several buttons and call the function within handlers for each type of button and change the argument passed to function
doAjax('someval');/* use in button 1*/
doAjax('someOtherval');/* use in button 2*/
function doAjax(arg) {
var someData = "";
if (arg == 'someval') {
someData = {
"yfilter": $("#yearFilter").val(),
"gfilter": $("#genreFilter").val()
};
} else {
someData = "sampleString";
}
$.ajax({
type: "POST",
url: "somefile.php",
cache: false,
data: someData,
dataType: "json",
success: function(data) {
if (arg == 'someval') {
alert("success 1");
} else {
alert("success 2");
}
}
})
}
Hope I've understood what you're asking for.
You could do something like this:
var parameters = {};
if (...) {
parameters = $("#yearFilter").serializeArray();
}
if () {
parameters = $("#genreFilter").serializeArray();
}
and then replace the line:
parameters: { "yfilter": $("#yearFilter").serializeArray(),
"gfilter": $("#genreFilter").serializeArray() },
with:
data: parameters,
JSON type should be best option for dynamically data. push whatever data you wish to inside json like shown below, Hence create your json dynamically and send as ajax data.
var employees = {
accounting: [],
dept: "HR"
};
employees.accounting.push({
"firstName" : item.firstName,
"lastName" : item.lastName,
"age" : item.age
});
$.ajax({
url: POSTURL,
type: 'POST',
dataType: 'json',
data : employees,
contentType: 'application/json; charset=utf-8',
success: function (results)
{
},
error: function (results)
{
jQuery.error(String.format("Status Code: {0}, ", results.status, results.statusText));
}
});
Try it:
someData = JSON.stringify({ yfilter: $("#yearFilter").val(), gfilter: $("#genreFilter").val() });
It will work.

how to clear a asp dropdown list and populate using ajax?

What i am trying to do is get a user to change one drop down, which then calls an ajax function which posts to the code behind (vb.net file) then clears and populates another asp dropdown list with the data returned from the function..hope i made sense
<script>
$(document).ready(function () {
$('.manuf').change(function () {
$.ajax({
type: "POST",
url: "ajax.aspx/GetModel",
data: '{' +
'ManufID:"' + $('.manuf').val() + '"' +
'}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var data = json_parse(msg.d);
if (data.error) {
alert("Error!");
return;
}
alert(data.model);
},
error: function(msg) {
alert('Get Details Failure: ' + msg);
}
});
});
});
</script>
My bad - you can write your ajax call like this -
$.ajax({ url :"/website/myurl", type:"POST", contentType:"application/json;", dataType:"json", data : "{ 'id' : '" + $("select[id*=selCurrentManuf]").val() + "' } ",
success : function (return_data) {
var data = $.parseJSON(return_data);
// code to add the contents of data to other list
$("select[id*=selCurrentModel]").empty().append($("<option>").attr("value","0").text("Choose..."));
// for the dropdown list clear all options and add a 'choose...' as the first option
$.each(data, function (i, d) { $("<option>").attr("value", d.k).text(d.v).appendTo($("select[id*=selCurrentModel]")); });
}, error:function () {
// handle error
}
});
I assume that you know how to fetch data from the backend via ajax. Something like this -
$.ajax({ url :"/website/myurl", type:"POST", dataType:"application/json"; data:"json",
success : function (return_data) {
var data = $.parseJSON(return_data);
// code to add the contents of data to other list
}, error:function () {
// handle error
}
});
Lets say you are getting it in a variable data which is an array.
You may try something like this -
$("select[id*=selCurrentModel]").empty().append($("<option>").attr("value", "0").text("Choose..."));
// for the dropdown list clear all options and add a 'choose...' as the first option
$.each(data, function (i, d) { $("<option>").attr("value", d.k).text(d.v).appendTo($("#ddlExperience")); });
// user $.each to iterate the data object which
You may try things on these lines.... Hope this helps.

Resources