How to call partial view through ajax in mvc3 - ajax

I need to call a partial view through ajax. I have tried the following, but I am not sure how to complete it.
$("#UserName").change(function () {
var userid = $("#UserName").val();
var ProvincialStateID = $("#State").val();
var Hobbyid = $("#Hobby").val();
var Districtid = $("#DistrictNames").val();
var Homeid = $("#Hobbyhome_EstablishmentId").val();
var urlperson = '#Url.Action("FetchPersonByUserName")';
$.ajax({
type: "POST",
url: urlperson,
data: { userid: userid, stateid: ProvincialStateID, hobbyid: Hobbyid, districtid: Districtid, homeid: Homeid },
success: function (data) {
//Dont know what to write here
});
});
Here is the function that I have written in my Controller:
[HttpPost]
public ActionResult FetchPersonByUserName(int userid,int stateid,int districtid,int homeid,int Hobbyid)
{
//Code to fetch the data in the partial using all parameters
return PartialView("_LearnerAssociationGridPartial", list);
}
When I click on a dropdown the ajax gets called and I want the function which is called through ajax to redirect it to the partial view. Please help me because currently I am not able to display my partial view

What you need is something like
$.ajax({
type: "POST",
url: urlperson,
data: { userid: userid,
stateid: ProvincialStateID,
hobbyid: Hobbyid,
districtid: Districtid,
homeid: Homeid },
success: function (data) {
var result = data;
$('targetLocation').html(result);
}
});
it is recomended to not use data straight from variable but you can.
Now target location is where you want the result to be displayed to.
See more information in here:
http://api.jquery.com/jQuery.ajax/
As to slow fetching data, try optimalize your query
Update
For nhibernate running slow, try http://www.hibernatingrhinos.com/products/nhprof which is nhibernate profiler, for paid version, or try sql profiler to see what is query is beeing executed, often you can get much more that you would expect and or really slow query due to complexity of the query.

I dont understand what you mean by redirect to the parial view. Usually people use ajax and Partial views to get part of a page without a page refresh ( you might have seen this kind of behaviour in this site/facebook/twitter etc..) So i guess you probably want to show the data you are fetching asynchronosly to be shown in a part of your current page. you can do that in your success handler
$.ajax({
type: "POST",
url: urlperson,
data: { userid: userid, stateid: ProvincialStateID, hobbyid: Hobbyid, districtid: Districtid, homeid: Homeid },
success: function (data) {
$("#divUserInfo".html(data);
}
});
Assumung you have a div with id divUserInfo in your current page.
If you really want to redirect after the ajax post, you can do it like this.
$.ajax({
type: "POST",
url: urlperson,
data: { userid: userid, stateid: ProvincialStateID, hobbyid: Hobbyid, districtid: Districtid, homeid: Homeid },
success: function (data) {
window.location.href="Why-I-need-Ajax-Then.php";
}
});
Personally, I dont use HttpPost (both in client and server) If it is a method to GET some data. I simpy use the jquery get or load.
$.get("yourUrl", { userid: userid, stateid: ProvincialStateID } ,function(data){
$("#divUserInfo".html(data);
});

Related

ASP.NET Core 2.2 Razor Pages - AJAX Call to page model not returning data

I am new to AJAX and cant even get the basics to function correctly.
I run an AJAX call from within a function in the javascript section from razor page but I cannot get the required string value to be returned.
The result I get in the alert box simply shows the HTML layout of the razor page as the message, as opposed to the actual string I want to return. I've spent hours trying to incorporate a X-CSRF-TOKEN in the header, but this makes no difference. I'm not sure the anti forgery token is required here and therefore the issue is before this step.
Razor Page:
$.ajax({
type: "GET",
url: "/Maps?handler=CanvasBackgroundImage",
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
Page Model:
public JsonResult OnGetCanvasBackgroundImage()
{
var result = "test message";
return new JsonResult(result);
}
Below is the code that is now working for me. Thanks for everyone's input.
Razor Page (script section):
function getMapBackgroundImagePath() {
// Get the image path from AJAX Query to page model server side.
$.ajax({
type: "GET",
url: "/Maps/Create?handler=MapBackgroundImagePath",
contentType: "application/json",
data: { imageId: imageId, }, // Pass the imageId as a string variable to the server side method.
dataType: "json",
success: function (response) {
copyText = response;
// Run the function below with the value returned from the server.
renderCanvasWithBackgroundImage();
},
});
}
Page model:
public JsonResult OnGetMapBackgroundImagePath(string imageId)
{
// Get the image full path where the id = imageId string
int id = Convert.ToInt32(imageId);
var imagePath = _context.Image.Where(a => a.ID == id)
.Select(i => i.ImageSchedule);
// return the full image path back to js query in razor page script.
return new JsonResult(imagePath);
}

mvc3 partialview doesn't load query string

I have Partial View that is updated with AJAX. The problem is that Partial View needs to take two parameters and one isn't in query string.
this is controller
public ActionResult _Unutrasnjost(string verzijaIme,int bojeId=0)
{
return PartialView(repositoryU.BojeUnutrasnjostVezano.Where(v =>v.VerzijaIme==verzijaIme&&v.BojeId == bojeId).ToList());
}
string verzijaIme is in query string but when the partialview is loaded it tells me that is undefined
int bojeId isnt in query string but when user clicks on button its send by AJAX.
I dont understand why everything is working if I put only one parameter (string or int) and if I put two parameters verzijaIme is undefined?
Its also working if I remove =0 from int bojeId and put that parameter in query string but I cant accept that kind of solution
Any suggestion?
Ajax code
function unutrasnjostData(id) {
var urlclear = '#Url.Action("_Unutrasnjost", "Configurator")' + "?bojeId=" + id;
$.ajax({
cache: false,
type: 'POST',
url: urlclear,
success: function (data) {
$('#meniDesnoIzmjeneUnutrasnjost').html(data);
}
});
}
Looks like you're not passing verzijaIme to partial view at all. You need to extend your unutrasnjostData function:
function unutrasnjostData(id, verzijaIme) {
var urlclear = '#Url.Action("_Unutrasnjost", "Configurator")' + "?bojeId=" + id + "&verzijaIme=" + verzijaIme;
$.ajax({
cache: false,
type: 'POST',
url: urlclear,
success: function (data) {
$('#meniDesnoIzmjeneUnutrasnjost').html(data);
}
});
}
Or, even better, send it in post:
$.ajax({
cache: false,
data: { bojeId: id, verzijaIme: verzijaIme },
type: 'POST',
url: urlclear,
success: function (data) {
$('#meniDesnoIzmjeneUnutrasnjost').html(data);
}
});
Don't confuse the query string from the request to the page with the query string from the AJAX call. Those are two separate requests.

Jquery ajax returning null values back to controller - MVC3

I'm using jQuery ajax to build a viewmodel list and then trying to send that viewmodel to another ActionResult in order to create PartialViews. The first part works well, and I'm able to create the viewmodel (List), but when I try to send the viewmodel back to the controller to build up the partial views, everything within the viewmodel is 0. It returns the correct number of items in the list, but it seems to lose the values.
Can anyone see if I'm missing anything here?
jQuery:
$.ajax({
async: false,
type: 'GET',
dataType: "json",
url: '#Url.Action("GetMapDetails")',
success: function (data) {
$.ajax({
async: false,
type: 'POST',
dataType: "json",
url: '#Url.Action("GetMapItems")',
data: {
list: data
},
success: function (list) {
//callback
});
}
});
}
});
and the controller:
public ActionResult GetMapDetails()
{
List<ViewModel> vm = new List<ViewModel>();
//create viewmodel here
return Json(vm.ToArray(), JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult GetMapItems(List<ViewModel> list)
{
return PartialView("_MapItemsPartial", list);
}
I've tried also using contentType: 'application/json' and JSON.stringify(data) but that gave me an Invalid JSON primitive error.
Any help appreciated - thanks
You could send them as JSON request:
$.ajax({
async: false,
type: 'POST',
contentType: 'application/json',
url: '#Url.Action("GetMapItems")',
data: JSON.stringify({
list: data
}),
success: function (result) {
//callback
}
});
Also notice that I have removed the dataType: 'json' parameter because your GetMapItems POST controller action doesn't return any JSON. It returns a PartialView. So I guess you did something wrong and this is not what it was meant to be returned from this controller action because from what I can see in your success callback you are expecting to manipulate JSON.
Oh, and please remove this async:false => it defeats the whole purpose of AJAX as you are no longer doing any AJAX, you are now doing SJAX.

jquery autocomplete using mvc3 dropdownlist

I am using ASP.NET MVC3 with EF Code First. I have not worked previously with jQuery. I would like to add autocomplete capability to a dropdownlist that is bound to my model. The dropdownlist stores the ID, and displays the value.
So, how do I wire up the jQuery UI auto complete widget to display the value as the user is typing but store the ID?
I will need multiple auto complete dropdowns in one view too.
I saw this plugin: http://harvesthq.github.com/chosen/ but I am not sure I want to add more "stuff" to my project. Is there a way to do this with jQuery UI?
Update
I just posted a sample project showcasing the jQueryUI autocomplete on a textbox at GitHub
https://github.com/alfalfastrange/jQueryAutocompleteSample
I use it with regular MVC TextBox like
#Html.TextBoxFor(model => model.MainBranch, new {id = "SearchField", #class = "ui-widget TextField_220" })
Here's a clip of my Ajax call
It initially checks its internal cached for the item being searched for, if not found it fires off the Ajax request to my controller action to retrieve matching records
$("#SearchField").autocomplete({
source: function (request, response) {
var term = request.term;
if (term in entityCache) {
response(entityCache[term]);
return;
}
if (entitiesXhr != null) {
entitiesXhr.abort();
}
$.ajax({
url: actionUrl,
data: request,
type: "GET",
contentType: "application/json; charset=utf-8",
timeout: 10000,
dataType: "json",
success: function (data) {
entityCache[term] = term;
response($.map(data, function (item) {
return { label: item.SchoolName, value: item.EntityName, id: item.EntityID, code: item.EntityCode };
}));
}
});
},
minLength: 3,
select: function (event, result) {
var id = result.item.id;
var code = result.item.code;
getEntityXhr(id, code);
}
});
This isn't all the code but you should be able to see here how the cache is search, and then the Ajax call is made, and then what is done with the response. I have a select section so I can do something with the selected value
This is what I did FWIW.
$(document).ready(function () {
$('#CustomerByName').autocomplete(
{
source: function (request, response) {
$.ajax(
{
url: "/Cases/FindByName", type: "GET", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.CustomerName,
value: item.CustomerName,
id: item.CustomerID
}
})
);
},
});
},
select: function (event, ui) {
$('#CustomerID').val(ui.item.id);
},
minLength: 1
});
});
Works great!
I have seen this issue many times. You can see some of my code that works this out at cascading dropdown loses select items after post
also this link maybe helpful - http://geekswithblogs.net/ranganh/archive/2011/06/14/cascading-dropdownlist-in-asp.net-mvc-3-using-jquery.aspx

How to filter occupation as you type in MVC3

I have a list of 2500 occupations held in our db. On our site we ask for you to enter your occupation and I would like it to filter the results as they type; like Play.com's search. Is there a way to do this in MVC3?
Appreciate any help.
You can do this using a autocomplete javascript.
For example:
http://www.pnpguidance.net/post/jQueryAutoCompleteASPNETMVCFramework.aspx
You can grab your data using jQuery Ajax.
I would create an action method that would return JSON:
[HttpGet()]
public JsonResult Occupations(String searchCriteria)
{
String[] occupations = new String[] { "Lawyer", "Carpenter" };
return Json(occupations.Where(s => s.Contains(searchCriteria))
.ToList(), JsonRequestBehavior.AllowGet);
}
If you run a GET request on this link: /Occupations?searchCriteria=Carpenter you'll receive ["Carpenter"] in a response.
I would make a jQuery ajax call to this action method. On success, I would take a reponse and generate an output such as list of li elements to select from.
Example of an ajax json get request is below:
$.ajax({
type: 'json',
url: '/Occupations',
type: 'GET',
cache: false,
data: { searchCriteria: searchCriteria},
error: function () {
},
success: function (result) {
alert(result);
}
});
This is from a notepad, so there might be some minor syntax errors.

Resources