Ajax request off an MVC Form - ajax

I am trying to do an ajax request and depending on the ajax request results I will allow the form to submit to the controller. However everytime the ajax request runs I get the error message.
Here is my javascript function:
function CheckForValidation(e) {
var scholarshipRequest = $("#scholars").val();
var aidYearRequest = $("#aidYear").val();
var amountRequest = $("#amount").val();
$.ajax({
type: "POST",
url: '#Url.Action("Validate_ScholarshipRequest", "RequestController")',
data: {
scholarshipId: scholarshipRequest,
aidYear: aidYearRequest,
amount: amountRequest
}
}).success(function(response) {
if (!response.success) {
e.preventDefault();
alert(success);
} else {
e.preventDefault();
}
}).error(function() {
e.preventDefault();
alert("Error on Submission");
});
}
This function is called from here:
$("#SubmitTutorRequestFrm").submit(function(e) {
e.PreventDefault();
CheckForValidation(e);
});
I try to debug the code and put a breakpoint on Validate_ScholarshipRequest but that method never gets called. The method signature is:
public ActionResult Validate_ScholarshipRequest(string scholarshipId, string aidYear, string amount)
This is the start of my form:
#using (Html.BeginForm("SubmitScholarshipRequest", "Request", FormMethod.Post, new { id = "SubmitTutorRequestFrm" }))

Just to get this officially answered and "closed", this was caused by a syntax-error:
url: '#Url.Action("Validate_ScholarshipRequest", "RequestController")',
Controller should not be included in the controller name. The correct action would then be:
url: '#Url.Action("Validate_ScholarshipRequest", "Request")',

Related

ASP.NET Core MVC AJAX call to Action method not working

I am new to AJAX and I am trying to get some data from my controller method into my .js file so I can use that data in my chart.
Everytime I run my project now I get the custom error message: "Error loading data! Please try again."
So that means that it is getting inside the AJAX function, but not successfully.
Also I dont know how to debug this properly to see where it goes wrong.
My .js code in a sepperate file is the following:
var chartData;
$(document).ready(function () {
$.ajax({
url: "/Account/GetChartData",
data: "",
dataType: "json",
type: "POST",
contentType: "application/json; chartset=utf-8",
success: function (data) {
chartData = data.d.toString();
alert("Data is: " + data.d.toString());
},
error: function () {
alert("Error loading data! Please try again.");
}
}).done(function () {
//After complete loading data
drawChart();
});
});
My controller method looks like this:
public static object[] GetChartData()
{
var chartData = new object[2];
//Manually adding some test data
chartData[0] = new object[]
{
"Day",
"Detected Asparaguses",
"String Operations",
"Successful Sting Operations"
};
chartData[1] = new object[]
{
"21-09-2018",
100,
85,
80
};
return chartData;
}
You have specified dataType: "json" but your method does not return json, and you would be getting a 500 (Internal Server Error). Change the method to return a JsonResult
[HttpPost]
public ActionResult GetChartData() // or `JsonResult`
{
var chartData = new object[2];
....
return Json(chartData);
}
and then data in the ajax callback will contain the array of your objects.

Ajax not returning desired results or not working at all

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.

Render partial view with AJAX-call to MVC-action

I have this AJAX in my code:
$(".dogname").click(function () {
var id = $(this).attr("data-id");
alert(id);
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'html',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
});
});
The alert gets triggered with the correct value but the AJAX-call does not start(the method does not get called).
Here is the method that im trying to hit:
public ActionResult GetSingleDog(int dogid)
{
var model = _ef.SingleDog(dogid);
if (Request.IsAjaxRequest())
{
return PartialView("_dogpartial", model);
}
else
{
return null;
}
}
Can someone see what i am missing? Thanks!
do you know what error does this ajax call throws?
Use fiddler or some other tool to verify response from the server.
try modifying your ajax call as following
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'string',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
error: function(x,h,r)
{
//Verify error
}
});
Also try
$.get("Home/GetSingleDog",{dogid : id},function(data){
$('#hidden').html(data);
});
Make sure, URL is correct and parameter dogid(case sensitive) is same as in controller's action method

How to use ajax in asp.net MVC

How can I return a class object from Ajax in asp.net MVC....???
Example:
Ajax call from html:
$.ajax({
type: 'POST',
url: '/Tutorial/Web/AlignmentRule/GetAlignmentDetails',
data: { alignmentRuleId: alignmentRuleId },
success:
function (data) {
alert(data.Id);
alert(data.alignmentData.Id);
$("#ruleName").val(data.alignmentData.Name);
$("#level").val(data.alignmentData.Id);
},
error:
function () {
alert("Server Error!!!!");
},
dataType: 'JSON',
async: false
});
and Action method in contorller is:
public virtual JsonResult GetAlignmentDetails(int alignmentRuleId)
{
var alignmentData = _allignmentRuleRepository.GetAlignmentById(alignmentRuleId);
return Json( alignmentData );
}
And I want to return a list of alignmentRule class objects also....
you can compose your return object as you want, for example, create a ViewModel as decorator to hold everything you want to pass, like:
var json = new JsonViewModel() {
alignmentData = alignmentData,
rules = yourRules
};
return Json(json);
The error is thrown because by default MVC framework does't allow you to respond to an HTTP GET request with a JSON (because of security reasons).
In order to make it work, when you retrurn Json in your action, you need to specify JsonRequestBehavior.AllowGet
[HttpPost]
public virtual JsonResult GetAlignmentDetails(int alignmentRuleId)
{
var alignmentData = _allignmentRuleRepository.GetAlignmentById(alignmentRuleId);
return Json( alignmentData, JsonRequestBehavior.AllowGet);
}
EDIT
Annotate your action with [HttpPost] attribute.
For further investigation on this topic check this article

How to get rid of this ajax form posting issue?

I am posting a form to controller action. I am getting an error from the controller.
This is the behavior I want:
If error - show the right error message on the same page without any page refresh.
If success - show the success message on the page again no page refresh
what I am getting is that the page gets fully refreshed with different url and shows this:
{"status":"Failed","msg":"\u0027Name\u0027 "}
The url changes to this: ../respond/update which is the action I post to
Basically I want to catch this Failed status and display the msg inside a span.
But why it is taking me to a different page?
Here is the view:
#using (Html.BeginForm("Update", "Respond", FormMethod.Post, new { id = "frmUpdate" }))
{
//have my form here
//submit button
}
Here is the js handler that posts the form:
$('#frmUpdate').submit(function () {
//validation
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
beforeSend: //show loader
success: function (result) {
alert(result.status);
},
error: function (xhr, status, error) { alert('error'); }
});
return false;
});
Here is controller:
[HttpPost]
public ActionResult Update(ResponseModel model)
{
return Json(new { status="Failed", msg = "Name" });
}
EDIT:
In Firefox it takes to differnt url.
But in IE8 I get this error from jquery itself. Interesting...
Message: Object doesn't support this property or method
Line: 28
Char: 12724
Code: 0
URI: /Content/js/external/jquery-1.6.2.min.js?v=3
I think you should stop the default submit behavior by doing so:
$('#frmUpdate').submit(function (e) {
e.preventDefault();
<your code here>
});
Otherwise the form submit will happen causing the behaviour you want to avoid.
Hope this helps.
#using (Html.BeginForm("Update", "Respond", FormMethod.Post, new { id = "frmUpdate" }))
{
//have my form here
//submit button
}
If you are using submit button than it will post the page. You need to use type button instead of submit.
It will work.
#using (Html.BeginForm("Update", "Respond", FormMethod.Post, new { id = "frmUpdate" }))
{
//have my form here
//use type button
}

Resources