4
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.
public IActionResult Getprojectsbylocation(int state_id)
{
var ds = _dal.Getprojectsbylocation(state_id);
var dt = ds.Tables[0];
List<Projects> li = new List<Projects>();
li = Helper.ConvertDataTable<Projects>(dt);
return PartialView("GetprojectsbylocationPartial",li);
}
//to do:- design partial view GetprojectsbylocationPartial with received Model (li in your case)
---this is main (parent) page
----everything will be in this page including scripts
<div id="smallArea"></div>
$('#button').click(function () {
$.ajax({
url: "/Company/Getprojectsbylocation",
type: "get",
dataType: "application/ json; charset = utf-8",
data: { state_id: $("#txtstateId").val() }
success: function(res)
{
$("#smallArea").html(res);
}
})
});
---end Main page----

2
Hi Gopi,
Based on your peoblem statement, please confirm the following point:
- Make sure that you have a view with the same name as the action method (in this case, Getprojectsbylocation) in the correct location within your project.
- Make sure that you are passing the correct data to the view. It looks like you are creating a list of Projects objects and then returning an empty view. You may need to pass the list of Projects to the view as a model.
return View(li);
-
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
1
Hello
You need to return data in ActionResult method. please check below sample code.
public ActionResult Getprojectsbylocation(int state_id)
{
var ds = _dal.Getprojectsbylocation(state_id);
var dt = ds.Tables[0];
List<Projects> li = new List<Projects>();
li = Helper.ConvertDataTable<Projects>(dt);
return Json(new { Data = li, JsonRequestBehavior.AllowGet });
}
In cshtml ajax call you need to write success method to get the data and bind to html where you need to update.
$('#button').click(function () {
$.ajax({
url: "/Company/Getprojectsbylocation",
type: "get",
dataType: "application/ json; charset = utf-8",
data: { state_id: $("#txtstateId").val() }
success: function (data) {
// write code to update html based on response data to preview.
}
})
});
Please check below link for more details:
https://www.c-sharpcorner.com/blogs/using-ajax-in-asp-net-mvc