Unable to load partial view on main view through Ajax in Razor Pages - ajax

The Ajax Request is:
$(document).ready(function() {
AddList();
})
function AddList(){
$.ajax({
url: "/Employees/Index?handler=OnGetPartial()",
type: "GET",
success: function (data) {
debugger
(".list").append(data);
}
});
}
OnGetPartial() is the action method in the index model that returns the partial view. The .list class is the container where the partial view is to be rendered.
Index model code:
public async Task<IActionResult> OnGetPartial()
{
Employee = await _context.Employee.ToListAsync();
return Partial("_ListPartialView", Employee);
}
The partial view does not load at all instead the main view gets loaded in the main view.

Here is a working demo:
ajax:
function AddList(){
$.ajax({
url: "/Employees/Index?handler=Partial",
type: "GET",
success: function (data) {
debugger
$(".list").html(data);
}
});
}
Pages/Shared/_ListPartialView.cshtml(Don't put #page into your partial view):
#model Employee
<h1>_ListPartialView</h1>

Related

Ajax and ASP.NET MVC- Get page URL, not the controller/action URL

I have an Ajax method that calls an MVC action from a controller class.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/ajax/Updates/Message",
dataType: "json",
success: function (response) {
//data variable has been declared already
data = response;
},
complete: function () {
if (data !== "") {
$('#div1').text(window.location.path);
$('#div2').text(data);
}
},
});
[HttpGet]
public async Task < ActionResult > Message()
{
string d = "test string";
return Json(d, JsonRequestBehavior.AllowGet);
}
The 'url' within the Ajax method is the call to the action method.
What to do if I want to return the actual page URL in Ajax Response, not the controller/action url?
So this controller does not have a view or anything associated with it, it is more like a helper class. When I am using ajax in any of the other pages, it is not returning the URL path of that specific page (via 'window.location.path) e.g. /Accounts/Summary , rather it is returning Updates/Message (in reference to the controller and action)
The web is stateless, when you call Updates/Message with ajax, it doesn't know it's for page Accounts/Summary. You'll have to pass this as parameter (post or get) or you could try Request.UrlReferrer which should contain the url of the page that called the request.
I hope this will help you try this code:
ajax code
$.ajax({
type: 'GET',
url: '#Url.action("Message","Updates")', // url.action(ActionName,ControllerName)
success: function (data) {
window.location = data;
},
error: function (xhr) { // if error occured
alert("Error occured.please try again");
}
dataType: 'json'
});
actionresult :
[HttpGet]
public async Task<ActionResult> Message()
{
string d = "http://www.google.com";
return Json(d, JsonRequestBehavior.AllowGet);
}

How do I request views from a layout using AJAX?

In my MVC application I don't want the layout page to reload everytime a view is selected. It would be great if the views could be loaded using ajax to keep things nice and fast and allow me to persist certain interface states that are wiped out when you move around.
My initial approach was to add some ajax to the _Layout.cshtml and then whent he view was requested pass that request to the controller method which will grab that page. All I ended up doing however was returning the WHOLE view again.
Here is the code I have so far, am I on the right tracks here or is this totally wrong?
Layout Ajax Script
<script>
$(function () {
var content = document.getElementById('content');
//When a user selects a link, pass the data attribute and
//use it to construct the url
$('#sidebar a').on("click", function () {
var page = $(this).data('page');
console.log("Data Attrib : " + page);
$.ajax({
type: 'GET',
url: '#Url.Content("~/Home/")' + page,
success: function (data) {
$('#content').html(data);
console.log("Success");
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("Error: " + thrownError);
}
})
})
});
</script>
As I say, this sort of works, but it's not perfect as it returns the whole page into the content area including layout, ideally I just want the core view data.
you can create a Single Page Application that have 1 layout and in home controller and index action method create menu or user setting or another things
and now you can load other action with Ajax call with data-content html that does not have layout file and append that in container
when user click another menu clean older content and add new or you can create tab strip or window
Layout.cshtml
<script>
$(function () {
//When a user selects a link, pass the data attribute and
//use it to construct the url
$('#sidebar a').on("click", function () {
var page = $(this).data('page');
$.ajax({
type: 'POST',
url: '/Home/Pages',
data: { pageValue: page },
success: function (data) {
$('#content').html(data);
console.log("Success");
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("Error: " + thrownError);
}
})
})
});
Controller
public class HomeController : Controller
{
[HttpPost]
public string Pages(string pageValue)
{
string result = //Whatever
return result;
}
}
Controller
public ActionResult SomeAction(String someparams)
{
//Make the model
SomeModel someModel = new SomeModel();
someModel.someparams = someparams;
return PartialView("SomePartialView", someModel);
}
In View
$.ajax({
url: "/Home/SomeAction",
type: "POST",
dataType : "html",
data: json,
contentType: 'application/json; charset=utf-8',
success: function(data){
$('#SomeDivID').html(data);
}
});

Rendar partial view in another partial view along with data model using jQuery .Ajax function

I am working on MVC 5 app and I want to render partialView in another partialview with model data using jQuery ajax function. when javaScript function is called, it suppose to send ID of selected element back to controller which is working fine, and in return bring partial view along with model which is not working from following code
<td>
<a href="#" class="SearchUser_Icon Hyperlink_Text" onclick="load_getUserListByGroupID(this)" id=#item.GroupID></a>
</td>
.
JavaScript function
function load_getUserListByGroupID(element)
{
var selectedGroupID = element.id;
alert(selectedGroupID);
$.ajax({
type: "POST",
url: "/UserManagement/SearchUsersByGroupID/",
dataType: "json",
data: { 'GroupID': selectedGroupID },
success: function (viewHTML) {
alert("success");
$("#userContentBlock").html(viewHTML);
},
error: function (errorData) { onError(errorData); }
}).done(function (result) {
alert("done!");
});
}
.
<div id="userContentBlock"></div>
Controller Method
[HttpPost]
public ActionResult SearchUsersByGroupID(string GroupID)
{
int intID = Convert.ToInt32(GroupID);
var UsersListByGroupID = _userServices.GetUsersByGroupID(intID);
return PartialView("GetUsersListByGroup_Partial", UsersListByGroupID );
}
You are returning HTML while expecting JSON in the ajax call. Just remove the dataType: "json" from the settings and everything should work as expected.
jQuery.ajax() dataType:
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response.

ajax call with jquery asp.net mvc

I have a button with the class "btn" and span with id "ajaxtest". When I click on the button I want to put text "test" in my span tag. And this to be done in ASP.NET MVC.
In the View I have the following ajax call:
<span id="ajaxtest"></span>
<input type="submit" class="btn" name="neverMind" value="Test BTN"/>
<script>
$(document).ready(function () {
$(".btn").click(function () {
$.ajax({
method: "get",
cache: false,
url: "/MyController/MyAction",
dataType: 'string',
success: function (resp) {
$("#ajaxtest").html(resp);
}
});
});
});
</script>
In MyController I have the following code:
public string MyAction()
{
return "test";
}
I know how Ajax works, and I know how MVC works. I know that maybe the error is because we are expecting something like this in the controller:
public ActionResult MyAction()
{
if (Request.IsAjaxRequest())
{
//do something here
}
//do something else here
}
But actually that is my problem. I don't want to call some partial View with this call. I just want to return some string in my span and I'm wondering if this can be done without using additional partial views.
I want to use simple function that will only return the string.
Change dataType: 'string' to dataType: 'text'
<script>
$(document).ready(function () {
$(".btn").click(function () {
$.ajax({
method: "get",
cache: false,
url: "/login/MyAction",
dataType: 'text',
success: function (resp) {
$("#ajaxtest").html(resp);
}
});
});
});
</script>
I check it my local it will work for me

Rendering a simple ASP.NET MVC PartialView using JQuery Ajax Post call

I have the following code in my MVC controller:
[HttpPost]
public PartialViewResult GetPartialDiv(int id /* drop down value */)
{
PartyInvites.Models.GuestResponse guestResponse = new PartyInvites.Models.GuestResponse();
guestResponse.Name = "this was generated from this ddl id:";
return PartialView("MyPartialView", guestResponse);
}
Then this in my javascript at the top of my view:
$(document).ready(function () {
$(".SelectedCustomer").change( function (event) {
$.ajax({
url: "#Url.Action("GetPartialDiv/")" + $(this).val(),
data: { id : $(this).val() /* add other additional parameters */ },
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
SetData(data);
}
});
});
function SetData(data)
{
$("#divPartialView").html( data ); // HTML DOM replace
}
});
Then finally my html:
<div id="divPartialView">
#Html.Partial("~/Views/MyPartialView.cshtml", Model)
</div>
Essentially when a my dropdown tag (which has a class called SelectedCustomer) has an onchange fired it should fire the post call. Which it does and I can debug into my controller and it even goes back successfully passes back the PartialViewResult but then the success SetData() function doesnt get called and instead I get a 500 internal server error as below on Google CHromes console:
POST http:// localhost:45108/Home/GetPartialDiv/1 500 (Internal Server
Error) jquery-1.9.1.min.js:5 b.ajaxTransport.send
jquery-1.9.1.min.js:5 b.extend.ajax jquery-1.9.1.min.js:5 (anonymous
function) 5:25 b.event.dispatch jquery-1.9.1.min.js:3
b.event.add.v.handle jquery-1.9.1.min.js:3
Any ideas what I'm doing wrong? I've googled this one to death!
this line is not true: url: "#Url.Action("GetPartialDiv/")" + $(this).val(),
$.ajax data attribute is already included route value. So just define url in url attribute. write route value in data attribute.
$(".SelectedCustomer").change( function (event) {
$.ajax({
url: '#Url.Action("GetPartialDiv", "Home")',
data: { id : $(this).val() /* add other additional parameters */ },
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
SetData(data);
}
});
});

Resources