jQuery ajax request results in a Not Found Error - c#

I' m new to MVC and was trying out some things but I can' t get this to work.
I have this script that should insert a partial view inside the page based on the dropdownlist selection.
$(function () {
$('#ddTipologiaFattura').change(function () {
var selectedID = $(this).val();
$.ajax({
url: '/Admin/Fatturazione/GetPartial/' + selectedID,
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html'
})
.success(function (result) {
$('#partialPlaceHolder').html(result);
})
.error(function (xhr, status, error) {
alert(status + '\n' + error)
});
});
});
This is my controller ~/Areas/Admin/Controllers/FatturazioneController.cs
[RouteArea("Admin")]
[Route("Fatturazione/{action}")]
public class FatturazioneController : Controller
{
private MyEntity db = new MyEntity();
public ActionResult GetPartial(int partialViewId)
{
if (partialViewId == 0)
{
var fatturaAziendaVM = new FatturaPerAziendaViewModel();
ViewBag.Intestatario = new SelectList(db.Azienda, "AziendaNome", "AziendaNome");
return PartialView("~/Areas/Admin/Views/Fatturazione/_ListaAziende.cshtml", fatturaAziendaVM);
}
var fatturaVM = new FatturaViewModel();
return PartialView("~/Areas/Admin/Views/Fatturazione/_Intestatario.cshtml", fatturaVM);
}
I keep getting a Not Found error by the script.
What am i doing wrong?

Your route only accounts for the action, not for the Id, which is why it's failing. You should either update the route per action to account for the Id, or append the id as a query string parameter.
$.ajax({
url: '/Admin/Fatturazione/GetPartial?partialViewId=' + selectedID,

Related

What is my controller action(.NET 6.0) and AJAX call returning 500 error?

I have an ajax call (GET) to a controller action to generate and return a url (JSON). When I run the code the ajax call goes but it never hits the controller action. I get a 500 error with no response text. I'm stumped. Below is my code, Thanks!
[HttpGet]
public ActionResult ViewOrderForm(int? id)
{
if (id == null || id == 0)
{
_logger.LogInformation("Order Id " + id + " does not exisit in the database. User is unable to view form.");
return NotFound("Order Id " + id + " does not exisit in the database.");
}
return Json(new
{
newUrl = Url.Action("ViewOrder", new { id = id })
}
);
}
function viewOrderForm(id) {
$.ajax({
url: siteURLS.ViewOrderForm,
method: "GET",
data: {
id: id
},
error: function (e) {
alert("Unable to open ITO form. " + e.responseText);
}
}).done(function (data) {
//alert(data.newUrl);
window.location.replace(data.newUrl);
});
}
Believe its type instead of method in ajax property
try this ajax,
$.ajax(
{
url: siteURLS.ViewOrderForm+"?id="+id,
type: 'GET',
dataType: 'json',
success: function (data) {
window.location.replace(data.newUrl);
},
error: function (e) {
alert("Unable to open ITO form. " + e.responseText);
}
});

Ajax call not redirecting to desired page using razor pages

I'm working on a .NET Core 3.1 razor pages project, and, on one of my pages, I have an AJAX call on submitting the form details. On clicking the button, I am hitting the post handler and ModelState is valid, but the post is not redirecting to the desired page. I have tried to debug the AJAX call using the devtools and my success and failure functions are not being hit.
Where am I going wrong?
Javascript
$.ajax({
url: "/Candidate/Add?handler=Candidate",
type: 'POST',
contentType: 'application/json',
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify(candidate),
success: function (data) {
//alert('success');
var t = data;
},
failure: function (data) {
var f = data;
}
})
Post handler
public async Task<IActionResult> OnPostCandidateAsync([FromBody] CandidateModel candidate)
{
if (!ModelState.IsValid)
{
IdTypeOptions = idTypeRepository.GetIDTypes().Result.Select(a => new SelectListItem
{
Value = a.Id.ToString(),
Text = a.Name
}).ToList();
industryOptions = industryRepository.GetIndustries().Result.Select(a => new SelectListItem
{
Value = a.Id.ToString(),
Text = a.Name
}).ToList();
GenderOptions = genderRepository.GetGender().Result.Select(g => new SelectListItem
{
Value = g.Id.ToString(),
Text = g.Name
}).ToList();
return Page();
}
//candidateModel.UserId =
var id = await candidateRepository.AddCandidate(candidate);
//return ()
return RedirectToPage("./Index");
}
Any help will be appreciated
ajax call always return some data, or partial view but never redirects inside of the action.
you have to fix on success of ajax
.....
data: ....,
success: function (data) {
window.location.href ...
//or
window.open(....)
},
error: function (jqXHR, exception) {
...error code
}
});
if you want to open another page use
window.location.href = 'http://...;' //the full url of razor page
if you want to open page in another window
window.open('the full url of razor page');
i had to return JsonResult on my post handler and passed the url i wanted to redirect to
public async Task<IActionResult> OnPostCandidateAsync([FromBody] CandidateModel candidate)
{
if (!ModelState.IsValid)
{
IdTypeOptions = idTypeRepository.GetIDTypes().Result.Select(a => new SelectListItem
{
Value = a.Id.ToString(),
Text = a.Name
}).ToList();
industryOptions = industryRepository.GetIndustries().Result.Select(a => new SelectListItem
{
Value = a.Id.ToString(),
Text = a.Name
}).ToList();
GenderOptions = genderRepository.GetGender().Result.Select(g => new SelectListItem
{
Value = g.Id.ToString(),
Text = g.Name
}).ToList();
return Page();
}
//candidateModel.UserId =
var id = await candidateRepository.AddCandidate(candidate);
return new JsonResult("/Candidate/Index");
//return ()
//return RedirectToPage("./Index");
}
and added the window.location.href on to the success function of the ajax call
$.ajax({
url: "/Candidate/Add?handler=Candidate",
type: 'POST',
contentType: 'application/json',
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify(candidate),
success: function (data) {
window.location.href = data;
},
failure: function (data) {
var f = data;
}
})
#Serge thank you for your assistance

Not Receiving the query result to ajax function from asmx page asp.net

I'm working with the Ajax and jQuery in my app. When I return a query result it's not showing me that result. The Code is given below:
asmx page Code
[WebMethod, ScriptMethod]
public void Getusertimelist(string id)
{
List<UserhoursList> employeelist = new List<UserhoursList>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcon"].ConnectionString))
{
con.Open();
SqlCommand command12 = new SqlCommand(" SELECT CONVERT(TIME, DATEADD(s, SUM(( DATEPART(hh, Total_time) * 3600 ) + ( DATEPART(mi, Total_time) * 60 ) + DATEPART(ss, Total_time)), 0)) From Todaywork Where Id='"+id+"'", con);
string getvalue = command12.ExecuteScalar().ToString();
UserhoursList employee = new UserhoursList();
employee.Total_Time = getvalue;
employeelist.Add(employee);
con.Close();
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(employeelist));
//return id;
}
Ajax Code
<script type="text/javascript">
$(document).on("click", ".get_time", function () {
var timeid = $(this).data('id');
$.ajax({
url: 'UserTotaltime.asmx/Getusertimelist',
method: 'post',
data: { id: timeid },
success: function (data) {
//alert(data);
},
error: function (err) {
}
});
});
$(document).ready(function () {
$(".get_time").click(function () {
$.ajax({
url: "UserTotaltime.asmx/Getusertimelist",
dataType: "json",
method: 'post',
success: function (data) {
alert(data[0].Total_Time);
// var prodetail = document.getElementById('textbox').HTML = 2;
document.getElementById("UserTime").innerHTML = data[0].Total_Time;
prodetail.html(data[0].Total_Time);
},
error: function (err) {
}
});
});
});
</script>
It's not showing me the answer because when I remove that (string id) parameter then it works perfectly. When I use it's not showing me the answer. I want to complete my project but this error not pushing me. Any help plz.
Your first request looks good. But in your second request, I don't see that you're using the jQuery DataTable data option.
$(".get_time").click(function () {
$.ajax({
url: "UserTotaltime.asmx/Getusertimelist",
dataType: "json",
method: 'post',
// Where is data: { id: timeid }?
success: function (data) {
alert(data[0].Total_Time);
// var prodetail = document.getElementById('textbox').HTML = 2;
document.getElementById("UserTime").innerHTML = data[0].Total_Time;
prodetail.html(data[0].Total_Time);
},
error: function (err) {
}
});
I think it will work if you change data to send a string
$.ajax({
url: 'UserTotaltime.asmx/Getusertimelist',
method: 'post',
data: '{ "id": ' + timeid + '}',
success: function (data) {
//alert(data);
},
error: function (err) {
}
});
an alternative is do something like
var dat = {}
dat.id = timeid
$.ajax({
url: 'UserTotaltime.asmx/Getusertimelist',
method: 'post',
data: JSON.stringify(dat),
success: function (data) {
//alert(data);
},
error: function (err) {
}
});

Ajax value not received by controller

I have this code that got properly delivered to its controller counterpart.
but for some reason the search model data was only nulls,while the pageNumber is received properly
did i made a mistake somewhere?
$("#NextResult").click(function () {
var xData= document.getElementById("x1").value;
var yData= document.getElementById("y1").value;
var searchModel = {
xval: xData,
yval: yData,
};
var pageNumber = #Model.Page +1;
$.ajax({
url: "/Work/FilterData",
type: "GET",
data: { 'searchModel': searchModel, 'pageNumber': pageNumber },
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
}).success(function (response) {
$('#datas').html(response)
})
});
the Controller is as such
[HttpGet]
public ActionResult FilterData(WorkSearchModel searchModel,int? pageNumber)
{
EDIT:
as suggested i tried doing doing both on a different project (this makes the function uncallable so i presume there's an error somewhere)
$("#NextResult").click(function () {
var xData= document.getElementById("x1").value;
var yData= document.getElementById("y1").value;
var searchModel = {
xval: xData,
yval: yData,
pageNumber = #Model.Page +1
};
$.ajax({
url: "/Work/FilterData",
type: "GET",
data: searchModel,
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
}).success(function (response) {
$('#datas').html(response)
})
});
i also have tried to do this but nothing works (this gives null values for both searchmodel and pagenumber now)
$.ajax({
url: "/Work/FilterData",
type: "GET",
data: JSON.stringify(searchModel, pageNumber),
contentType: "application/json;",
I would change the call from a GET to POST
One solution is to send the parameters one by one in the query string like this
$("#NextResult").click(function () {
var xData= document.getElementById("x1").value;
var yData= document.getElementById("y1").value;
var pageNumber = #Model.Page +1;
$.ajax({
url: "/Work/FilterData?xval=xData&yval=yData&pageNumber=pageNumber",
type: "GET",
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
}).success(function (response) {
$('#datas').html(response)
})
});
And the controller
[HttpGet]
public ActionResult FilterData(int xval, int yval, int? pageNumber)

How to get the Selected ID from DropDownList selection changed from View to Controller

I have a DropDownList in my View and I want to capture the ID of the selected value from both the DropDownList and pass that value as an argument in one of my Controller action method.
#Html.DropDownList("ddlL", new SelectList(string.Empty, "Value", "Text"), "Select")
<script type="text/javascript">
$("#ddlL").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("LoadLDet")',
datatype: 'JSON',
success: function (data) {
$("#ddlL").append('<option value=' + '0' + '>' + 'Select' + '</option>');
$.each(data, function (key, value) {
$("#ddlL").append('<option value=' + value.LId + '>' + value.LName + '</option>');
});
},
error: function (ex) {
alert('Failed to display Data');
}
});
$("#ddlL").change(function () {
$("#ddlW").empty();
var LID=$(this).val();
alert(LID);
$.ajax({
type: 'POST',
url: '#Url.Action("GetWTest")',
datatype: 'JSON',
data: { LocID: $("#ddlL").val() },
success: function (data) {
$("#ddlW").append('<option value=' + '0' + '>' + 'Select' + '</option>');
$.each(data, function (key, value) {
$("#ddlW").append('<option value=' + value.WinId + '>' + value.WinName + '</option>');
});
},
error: function (ex) {
alert('Failed to load Win data');
}
});
return false;
});
</script>
Here With the help of LoadLDet() I am getting all the data and binding it in first DropDownList ddlL. And then passing the LocID getting from Change Event function of DropDownList ddlL to JsonResult GetWin() to bind the data of second DropDownList ddlW.
[HttpPost]
public JsonResult LoadLDet()
{
MyService.ServiceInfoClient Service = new MyService.ServiceInfoClient();
var Loc = Service.GetLocList();
return Json(Loc);
}
public JsonResult GetWin(string LocID)
{
MyService.ServiceInfoClient Obj = new MyService.ServiceInfoClient();
IEnumerable<MyService.Win> Win = Obj.GetWinByLocId(Convert.ToInt32(LocID));
return Json(Win);
}
I have another ActionResult ExportDataInExcel() class in which I want to pass selected DropDownList items LId and WId as argument in one of the method which I am calling to get data which needs to be exported. Please guide me how I can pass "LId" from view to controller which I am capturing in the Ajax also how can I pass WId i.e. the second DropDownList ID from View to below mentioned Action Method.
public ActionResult ExportDataInExcel()
{
ExportData(LId, WId, xyz);
return View("Index");
}
Take a look at this code. I used data to list all of the parameters that I want to send to server. I modified your code. I used getJSON method to fetch the JSON from the server. It's a little bit simpler.
<script type="text/javascript">
$("#ddlL").empty();
// Get data from LoadLDet action.
$.getJSON('#Url.Action("LoadLDet")', function(data) {
$("#ddlL").append('<option value="0">Select</option>');
$.each(data, function (key, value) {
$("#ddlL").append('<option value=' + value.LId + '>' + value.LName + '</option>');
});
});
// Send data to ExportDataInExcel action.
$("#ddlL").on('change', function() {
var lId = $(this).val();
var wId = $("#otherDropdownId").val();
$.ajax({
type: 'POST',
url: '#Url.Action("ExportDataInExcel")',
datatype: 'json',
data: {
LId: lId, // FIRST DROPDOWN VALUE
WId: wId // SECOND DROPDOWN VALUE
},
success: function (data) {
alert("Data successfuly sent.");
},
error: function () {
alert("Error occured while sending the data.");
}
});
});
</script>
Your action that receives parameter.
public ActionResult ExportDataInExcel(int LId, int WId)
{
ExportData(LId, WId, xyz);
return View("Index");
}
this can help
$("#ddlL").on('change', function() {
var id =$(this).val(); // here's your value
alert(id); // show your value
// do your ajax call here
});

Categories