This ajax works fine but the controller does not return the view. It returns either blank view or returns inappropriate View. How can I solve this issue.
Getprojectsbylocation(int state_id)
{
var ds = _dal.Getprojectsbylocation(state_id);
var dt = ds.Tables[0];
List li = new List();
li = Helper.ConvertDataTable(dt);
return View();
}
My controller code:
public IActionResult Getprojectsbylocation(int state_id)
{
var ds = _dal.Getprojectsbylocation(state_id);
var dt = ds.Tables[0];
List li = new List();
li = Helper.ConvertDataTable(dt);
return View();
}
Ajax call:
$('#button').click(function () {
$.ajax({
url: "/Company/Getprojectsbylocation",
type: "get",
dataType: "application/ json; charset = utf-8",
data: { state_id: $("#txtstateId").val() }
})
});
Sachin SinghPosted Dec 19, 2022, 5:17 AM
Do you know why do we use ajax?
Ajax makes internal request without refreshing the page. So you are getting the view but as you are not doing anything with the returned view you are seeing the old page from where the request was issued.
That is why we prefer to send json and built dynamic control with json data on ajax success.
However you can always return partialview and assign it to a part of main page inside ajax success.
Deepak TewatiaPosted Dec 19, 2022, 5:12 AM
Hi Gopi,
Based on your peoblem statement, please confirm the following point:
Check for any errors or exceptions that may be occurring when the action method is executed. These could be causing the view not to be returned correctly.
Check the response from the server to see if there are any errors or issues that may be causing the view not to be returned correctly.
Thanks
Vishal JoshiPosted Dec 19, 2022, 5:11 AM
Hello
You need to return data in ActionResult method. please check below sample code.
In cshtml ajax call you need to write success method to get the data and bind to html where you need to update.
Please check below link for more details:
https://www.c-sharpcorner.com/blogs/using-ajax-in-asp-net-mvc