AJAX Post method not hitting controller - asp.net-mvc

Can anyone point me here, what's wrong I am doing? my controller not hitting on Ajax post
Ajax Code
<script type="text/javascript">
$(document).ready(function () {
$('#btncreate').click(function () {
var projectid = $("#txtprojectid").val();
var financetype = $("#txtfinancetype").val();
var actualcost = $("#txtactualcost").val();
$.ajax({
url: 'Projects/CreateFinanceItems?pid=' + projectid + "&ft=" + financetype + "&ac=" + actualcost,
datatype: 'json',
success: function (response) {
alert("Yes");
if (response != null) {
$('#displayproContainer').load('/Projects/PartialprojectFinanceItem');
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
})
});
});
</script>
Controller Code
[HttpPost]
public ActionResult CreateFinanceItems(string pid, string ft, string ac)
{
return View();
}

First of all , you have forget to specify the type of request in your Ajax. the default one is Get.
Second thing you have to start the url of the request with / which means the root URl of the site followed by the path of of the Action result.
<script type="text/javascript">
$(document).ready(function () {
$('#btncreate').click(function () {
var projectid = $("#txtprojectid").val();
var financetype = $("#txtfinancetype").val();
var actualcost = $("#txtactualcost").val();
$.ajax({
url: '/Projects/CreateFinanceItems?pid=' + projectid + "&ft=" + financetype + "&ac=" + actualcost,
type: 'POST',
datatype: 'json',
success: function (response) {
alert("Yes");
if (response != null) {
$('#displayproContainer').load('/Projects/PartialprojectFinanceItem');
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
})
});
});
</script>

Related

Unable to send array data using ajax with ASP.NET Core and Entity Framework Core

I am trying to send array to the controller but it's blank in the controller parameter.
Ajax function is:
$('#pending').click(function () {
SaveTestResult("/Reception/PatientTests/SavePendingTest");
});
function SaveTestResult(url) {
var pid = $('.patientId').attr('id');
var tid = "";
var tval = "";
var tpid = "";
var tests = [];
$("table > tbody > tr").each(function () {
testId = $(this).find('.tid').val();
if (typeof (testId) != "undefined") {
tid = testId;
}
var rowText = ""
$(this).find('td').each(function () {
tpid = $(this).find('.tpId').val();
tval = $(this).find('.result').val();
if (typeof (tpid) != "undefined") {
tests.push({ PatientId: pid, TestId: tid, TestParameterId: tpid, TestValue: tval });
}
});
});
// alert(JSON.stringify(tests));
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(tests),
contentType: "application/json",
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
success: function (data) {
alert(data);
},
error: function (e) {
alert('Error' + JSON.stringify(e));
}
});
}
This is the controller method:
[HttpPost]
[Route("Reception/PatientTests/SavePendingTest")]
public async Task<IActionResult> SavePendingTest(List<PendingTestResult> pendingTestResult)
{
if (ModelState.IsValid)
{
foreach (PendingTestResult ptr in pendingTestResult)
{
_db.Add(ptr);
await _db.SaveChangesAsync();
}
// return new JsonResult("Index");
}
return new JsonResult(pendingTestResult); ;
}
But when run the code I see data array filled but inside of the SavePendingTest action, pendingTestResult is empty and not filled! I also tried the [FromBody] tag inside action params, but it does not work either!
Help me resolve this
you are sending a string with no names so the controller can not get the values.
change you code to
$.ajax({
type:"POST",
url:url,
data:test
...
});
the test should be an object not a string.
You can pass the list of objects by :
$.ajax({
type: "POST",
url: "Reception/PatientTests/SavePendingTest",
data: { pendingTestResult: tests },
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
success: function (data) {
alert(data);
},
error: function (e) {
alert('Error' + JSON.stringify(e));
}
});
pendingTestResult in data:{ pendingTestResult: tests } matches the parameter name on action and remove the contentType setting .

How can get image with Jquery Ajax

I can can get picture by Razor '#Action' but with Ajax Can't. I write
in controller:
public ActionResult getCommodityPic()
{
var f= File(Server.MapPath("~/App_Data/CommodityPics/eee/1") + ".jpg", "image/jpg");
return f;
}
and in java script :
$(document).ready(function () {
ShowCommodities();
getCommodityPic();
});
function getCommodityPic() {
$.ajax({
url: '#Url.action("getCommodityPic")',
type: 'Get',
dataType: 'image/jpg',
success: function (Data, Status, jqXHR) {
$('#img1').attr('src', Data);
}
});
$.ajax({
url: '#Url.Action("DownloadPic", "MyController")',
contentType: 'application/json; charset=utf-8',
datatype: 'json',
data: {
id: Id
},
type: "GET",
success: function (Data, Status, jqXHR) {
if (Data != "") {
alert("Empty");
return;
}
window.location ='#Url.Action("DonloadPic","Mycontroller")';
}
});
in Controller:
public ActionResult DownloadPic(int? id)
{
Lesson l = new Lesson();
l = db.Lesson.Single(p => p.id == id);
if (l.picture == null)
{
string targetFolder = System.Web.HttpContext.Current.Server.MapPath("~/Image/book-03.jpg");
byte[] img = System.IO.File.ReadAllBytes(targetFolder);
return File(img, "image/jpg");
}
return File(l.picture, "image/jpg");
}
If you want to display the image dynamically, then try this. You may not need an Ajax call for this.
$('#img1').html('<img src="getCommodityPic" />')
If you want to process the image (read its raw binary) then this answer should help - https://stackoverflow.com/a/20048852/6352160

Getting 500 error while return object to ajax call

I am getting error when I am trying to return result to my ajax call. Getting 500 error every time I try to return the data. Here is my ajax call:
I am getting error when I am trying to return result to my ajax call. Getting 500 error every time I try to return the data. Here is my ajax call:
$("#UserActivation").change(function () {
var userID = $("#UserActivation").val();
var searchPic;
var planID = $("#planid").val();
debugger;
$.ajax({
type: "GET",
url: "/Home/GetUserImage",
data: { userID: userID, type: 'Activation', planID: planID },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
debugger;
alert(response);
},
error: function (xhr, ajaxOptions, thrownError){
debugger;
alert(xhr.responseText);
},
complete: function (a) {
// Handle the complete event
debugger;
alert("ajax completed ");
}
});
return false;
});
And my Controller function is:
[HttpGet]
public JsonResult GetUserImage(string userID, String type, string planID)
{
if (userID != null && type != null && planID != null)
SaveUser(planID, userID, type);
DataSet ds = SQL_DB.ExecuteDataSet("SELECT * FROM [M_UserRegistration] where [ActiveFlag] = 1 and UserId='" + userID + "'");
UserData userData = new UserData();
if (ds.Tables[0].Rows.Count > 0)
{
userData.UserID = Convert.ToString(ds.Tables[0].Rows[0]["UserId"]);
userData.UserImage = "../../Images/Users/" + Convert.ToString(ds.Tables[0].Rows[0]["UserImage"]);
userData.UserName = Convert.ToString(ds.Tables[0].Rows[0]["UserFirstName"]) + " " + Convert.ToString(ds.Tables[0].Rows[0]["UserLastName"]);
}
return Json(userData);
}
Getting 500 error in the error of ajax.
You have to allow json data for request type GET like following. Hope this will solve your problem.
return Json(userData, JsonRequestBehavior.AllowGet);

How To Get An Array Of MVC Partial View with Jquery

I want to call a method in my controller via ajax with jQuery, and analyse the response in the successcallback. But I want to send a array of partialview to this response, like in the following example:
$.ajax({
url: '/Admin/Design/ChangeQuestionType',
type: 'POST',
data: {
viewname: viewname,
questionid: questionid,
questiontypeid:questiontypeid,
pageid: pageid
},
success: function (response) {
jQuery.each(response, function (i) {
console.log(response);
$('.questionvalidation').html(response[i])
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
console.log(xhr.responseText);
alert(thrownError);
}
});
and controller is :
public ActionResult ChangeQuestionType(string viewname, int questionid, int questiontypeid, int pageid)
{
var viewbody = PartialView(viewname);
var viewtitle = PartialView("Title");
List<ActionResult> responselist = new List<ActionResult>();
responselist.Add(viewbody);
responselist.Add(viewtitle);
return Json(responselist, JsonRequestBehavior.AllowGet);
}
When the code is executed console.log() outputs :

MVC: pass parameter to action using Jquery.ajax()

I'm pretty new to MVC. I need to make ajax call to an Action with parameters using html.Action(). I'm unable to pass this..
Hope it will be helpful for other MVC begineers as well..
HTML:
<%: Html.ActionLink("Add Race", "AddRace",
new {eventId = Model.EventId, fleetId=Model.SelectedFleet.ID},
new{#onclick=string.Format("return checkFleetAddedandScroing()")}) %>
Jquery:
function checkFleetAddedandScroing() {
debugger;
$.ajax({
type: "GET",
url: '<%=Url.Action("CheckFleetExists")%>',
dataType: "json",
cache: false,
success: function (data, textStatus) {
data = eval("(" + data + ")");
if (data == true) {
return true;
}
else {
alert("Cannot Add race becasue you have not yet added any fleets and fleet scoring is checked.");
return false;
}
}, //success
error: function (req) {
}
});
}
Action:
public JsonResult CheckFleetExists(Guid fleetId )
{
bool exists = false;
try
{
exists = !db.Races.Any(r => r.FleetID == fleetId);
}
catch
{
}
return Json(exists, JsonRequestBehavior.AllowGet);
}
I need to pass fleetid to action which is in Model.SelectedFleet.ID. Its being used somewhere on pages. But i'm unable to use that somehow..
please suggest where i'm doing wrong...
It looks like you are trying to invoke a controller action using AJAX when the link is clicked and depending on the result of this call either allow the user to be redirected to the actual AddRace action or be prompted with an error message.
The problem with your code is that you are attempting to return true/false from within the success AJAX callback which doesn't make any sense. You need to always return false from the click callback and inside the success callback, depending on the returned value from the server, redirect manually using the window.location.href function.
HTML:
<%: Html.ActionLink(
"Add Race",
"AddRace",
new {
eventId = Model.EventId,
fleetId = Model.SelectedFleet.ID
},
new {
data_fleetid = Model.SelectedFleet.ID,
#class = "addRace"
}
) %>
Jquery:
<script type="text/javascript">
$(function () {
$('.addRace').click(function (evt) {
$.ajax({
type: 'GET',
url: '<%= Url.Action("CheckFleetExists") %>',
cache: false,
data: { fleetId: $(this).data('fleetid') },
success: function (data) {
if (data.exists) {
// the controller action returned true => we can redirect
// to the original url:
window.location.href = url;
}
else {
alert("Cannot Add race becasue you have not yet added any fleets and fleet scoring is checked.");
}
},
error: function (req) {
}
});
// we make sure to cancel the default action of the link
// because we will be sending an AJAX call
return false;
});
});
</script>
Action:
public ActionResult CheckFleetExists(Guid fleetId)
{
bool exists = false;
try
{
exists = !db.Races.Any(r => r.FleetID == fleetId);
}
catch
{
}
return Json(new { exists = exists }, JsonRequestBehavior.AllowGet);
}
Remark: inside your AddRace controller action don't forget to perform the same verification as you are doing inside your CheckFleetExists. The user could simply disable javascript and the AJAX call will never be done.
change your action like this :
public JsonResult CheckFleetExists(string fleetId)
{
var fleetGuid = Guid.Parse(fleetId);
bool exists = false;
try
{
exists = !db.Races.Any(r => r.FleetID == fleetGuid );
}
catch
{
}
return new JsonResult{ Data = exists};
}
and change you ActionLink so :
<%: Html.ActionLink("Add Race", "AddRace",
new {eventId = Model.EventId, fleetId=Model.SelectedFleet.ID},
new{onclick=string.Format("return checkFleetAddedandScroing({0})",Model.SelectedFleet.ID)}) %>
and your script block may look something like this :
function checkFleetAddedandScroing($fleetId) {
$.ajax({
type: "POST",
url: '<%=Url.Action("CheckFleetExists")%>',
dataType: "json",
data : { "fleetId" : $fleetId },
cache: false,
success: function (data, textStatus) {
data = eval("(" + data + ")");
if (data == true) {
return true;
}
else {
alert("Cannot Add race becasue you have not yet added any fleets and fleet scoring is checked.");
return false;
}
}, //success
error: function (req) {
}
});
}
Problem was in answers that url to action was not complete..i did it using this way
function checkFleetAddedandScroing() {
// debugger;
$.ajax({
type: "POST",
url: '<%=Url.Action("CheckFleetExists", new {eventId=Model.EventId})%>',
dataType: "json",
cache: false,
success: function (data, textStatus) {
data = eval("(" + data + ")");
if (data == true) {
return true;
}
else {
alert("Cannot Add race becasue you have not yet added any fleets and fleet scoring is checked.");
return false;
}
}, //success
error: function (req) {
}
});
}

Resources