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

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.

Related

Display data on selected item with Laravel and Ajax

I'm trying to display the selected data from table to a modal using Ajax but seems no working. I used the restful routing in laravel. Data is successfully fetched but I'm stuck in displaying it inside the modal.
Controller:
public function show($project)
{
$project = Project::find($project);
return \Response::json($project);
}
Ajax:
$.ajax({
url: url,
data: data,
method: 'GET',
success: function(data) {
console.log(data)
$("#editProject").modal('show');
$('#editProject').find('.modal-body').html(data);
}
})
From console:

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);
}
});

Return HTML (including images) via Json ASP .NET MVC4

How can I return a Partial view result to view by using Ajax and Json, I am working in ASP .NET MVC4 structure. The html also include images. here I am using code to return data that is not working properly.
return PartialView("_OnlineUsers", online_users);
Can I return data in form of HTML(including images) through json???
Write your ajax call like this
$('.btnSubmit').on('click', function(){
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: 'post',
cache: false,
async: true,
data: { id: "ID" },
success: function(result){
$('.divContent').html(result);
}
});
});
on your controller
public PartialViewResult Action(int id){
var online_users = //populate your model
return PartialView("_OnlineUsers", online_users);
}
No, you can't return html and json with same ajax request.Another way to get the partial view is
$.get('#Url.Action("yourActionName","YOurControllerNme")',function(data){
$('#YourDivId').html(data);
});
There is nothing wrong in your server side code
To get the Image you may use
<div class="display-field">
<img src="#Url.Action("getPhotoAction", "ControllerName", new { id = Model.Id })"
title="#Model.TitleYouWantToSer"/>
</div>

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);
}
});
});

call controller using ajax failing to find controller

I am trying to call a controller via ajax without to much luck.
I have create this in my view
<input type="submit" id="preview-email" value="Preview Email" />
<script type="text/javascript">
$("#preview-email").click(function () {
var p = { "email": "1223" };
$.ajax({
url: '/BusinessController/PreviewEmail',
type: "POST",
data: p,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function () {
alert("error");
}
});
});
</script>
My controller
[HttpPost]
public ActionResult PreviewEmail(string email)
{
// string d = ViewData["editor"].ToString();
string e = System.Web.HttpUtility.HtmlDecode(email);
EmailModel model = new EmailModel() { EmailBody = e };
return PartialView("_PreviewEmail", model);
}
Turning on fiddler is telling me that its a 500 error. What have I done wrong? I've placed a breakpoint on my controller however it doesnt get that far
Your URL should be:
'/Business/PreviewEmail'
instead of:
'/BusinessController/PreviewEmail'
However, the recommended practice for building URLs is to use your routes:
Url.Action("PreviewEmail", "Business")
BTW, you have another problem in your code. By setting "application/json" as your contentType, MVC will expect a JSON string. However, when you assign a JavaScript object to the data property of $.ajax(), jQuery will serialize the value to this:
email=1223
So you'll want to assign a string to the data property instead by doing this:
var p = '{ "email": "1223" }';
#Url.Action doesn't work inside the JS file. What if my call to Controller/Action is inside JS file?
For now I'm, retrieving the location.href and then replacing the Action name.
(This may not be a wise thing to do)

Resources