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);
}
});
});
Related
I have seen numerous examples, mostly wrong or outdated concepts written a decade ago. I cant seem to find a way to submit multiple variables to the ef core database using Ajax. I can get it to work with one, but cant seem to get it to work with multiple. Not sure if I am doing something wrong? I just get a syntax error on the var dataObjects
Ajax Call
<script type="text/javascript">
$("#cosubmitbutton").click(function () {
if ($('#CompanyId').val() == "-1" || $('#CompanyId').val() == "0") {
toastr.warning("Please select company / Client!");
return false;
}
var dataObjects = {
CompanyId = $("#CompanyId").val();
TechnicalContact = $("#TechnicalContactId").val();
TCEmailAddress = $("#TCEmailAddressId").val();
NumOfWorkstations = $("#NumOfWorkstationsId").val();
NumOfUsers = $("#NumOfUsersId").val();
NumOfServers = $("#NumOfServersId").val();
NumOfFirewalls = $("#NumOfFirewallsId").val();
NumOfSwitches = $("#NumOfSwitchesId").val();
NumOfAps = $("#NumOfApsId").val();
Domain = $("#DomainId").val();
};
//ObjThreadItem = JSON.stringify({ 'ObjThread': ThreadItem});
console.log("Json Stringify CommonPostData: ", JSON.stringify(dataObjects))
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'JSON',
url: '/Onboarding/Client/CreateClientOverview',
type: "post",
data: JSON.stringify(dataObjects),
success: function (result) {
debugger
toastr.success("Information successfully updated on server!");
location.reload();
},
failure: function (response) {
debugger
console.log(response);
}
});
});
</script>
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult CreateClientOverview(ClientOverview Modal)
{
_context.ClientOverview.Add(Modal);
_context.SaveChanges();
return Json(Modal);
}
I have been trying to load return a JsonResults action from a controller in MVC using ajax call. I can see that the alert() function is triggering well but the ajax is not executing. I have search for several sources but to no avail.
public JsonResult FillBusinessLicenceL3(int? selectedID)
{
var bl3_Items = db.LevelThreeItems.Where(l3 => l3.LevelTwoItem_ID == selectedID);
return Json(bl3_Items, JsonRequestBehavior.AllowGet);
}
The below too is the javascript calling for the json method.
<script>
function FillBussLicence_L3items() {
alert("You have clicked me");
var bl2_Id = $('#BussLicenceL2_ID').val();
//alert(document.getElementById("BussLicenceL2_ID").value);
alert(bl2_Id);
$.ajax({
url: 'StartSurvey/FillBusinessLicenceL3/' + bl2_Id,
type: "GET",
dataType: "JSON",
data: "{}", // { selectedID : bl2_Id },
//contentType: 'application/json; charset=utf-8',
success: function (bussLicence_L3items) {
$("#BussLicenceL3_ID").html(""); // clear before appending new list
$.each(bussLicence_L3items, function (i, licenceL3) {
$("#BussLicenceL3_ID").append(
$('<option></option>').val(licenceL3.LevelThreeItem_ID).html(licenceL3.LevelThreeItem_Name));
});
}
});
}
Also, I have tried this one too but no execution notice.
Thanks a lot for your help in advance.
After looking through the browser's console, I noticed that the LINQ query was tracking the database and was creating a circular reference so I changed the query to the following and voila!!
public JsonResult FillBusinessLicenceL3(int? selectedID)
{
var bl3_Items = db.LevelThreeItems.
Where(k => k.LevelTwoItem_ID == selectedID).
Select(s => new { LevelThreeItem_ID = s.LevelThreeItem_ID, LevelThreeItem_Name = s.LevelThreeItem_Name });
return Json(bl3_Items, JsonRequestBehavior.AllowGet);
}
There was nothing wrong with the ajax call to the controller.
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"
The below mentioned code not redering the page. is there anything need to be added with this.
[HttpPost]
public ActionResult CompetitiveSnapshotDetails(Object[] comp)
{
CompetitiveSnapModel[] compSnapList = new JavaScriptSerializer().Deserialize<CompetitiveSnapModel[]>(comp[0].ToString());
String[] competitiveDetailHeader = { "State", "Rank", "Terracon Inc Transcations", "Number 1 Firm", "Number 2 Firm", "Number 3 Firm", "Total Transcations" };
ViewData["CompetitiveDetailHeader"] = competitiveDetailHeader;
ViewData["CompetitiveDetail"] = compSnapList;
return View();
}
Call this using ajax
$("#com-snap").click(function () {
var competitiveSnap = JSON.parse(window.localStorage.getItem("l_compSnap"));
var URL = "../Detailpage/CtDetails";
$.ajax({
cache: false,
type: "POST",
url: URL,
data: { comp: JSON.stringify(competitiveSnap)},
dataType: "json",
success: function (data) {
},
error: function (xhr) {
}
});
});
What I see is that in you AJAX code, you are not calling the same action you showed first.
The URL you need to put is more like:
"/YourController/CompetitiveSnapshotDetails"
The second and more important issue is that your need to grab the html of your view and do something with it.
Your VIEW HTML is in your data parameter in your success function.
Something like this: $('#YourContainer').html(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.