mvc3 partialview doesn't load query string - asp.net-mvc-3

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.

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

Returning data objects from ajax query to controller

I'm attempting to access data from a form and pass it to a controller in MVC.
I was successful in passing the data when I get the element by ID and pass as string:
This works:
data: JSON.stringify({
'Answer0': $("#Answer0").val(),
'Answer1': $("#Answer1").val(),
'Question0': $("#Question0").val()
}),
However I want to bring the data in as a viewmodel. When I specify the request as:
data: JSON.stringify($('#' + formDiv).serializeObject()),
It will populate the viewmodel, however there are fields that are not bound to the ViewModel that I would like to pass along with the serialized form. I have tried just adding them, but they don't seem to come in if I pass both the serialized form object and the additional string.
function clickedNext(e, formDiv) {
var sURL = '#Url.Action("SurveySave", "Home")'
$.ajax({
url: sURL,
type: "POST",
contentType: 'application/json',
data: JSON.stringify($('#' + formDiv).serializeObject(), { 'Answer0': $("#Answer0").val(), 'Answer1': $("#Answer1").val() }),
success: function (data) {
//$('#InvestigationStatus').html(data);
}
});
Controller
[HttpPost]
public ActionResult SurveySave(SurveyViewModel s, string Answer0, string Answer1)
I feel like you can't put two objects inside of JSON.stringify();
Maybe try something like:
var bothObjects = {
$('#' + formDiv).serializeObject(),
{ 'Answer0': $("#Answer0").val(), 'Answer1': $("#Answer1").val() }
}
...
JSON.stringify(bothObjects),

ASP.NET & Ajax - How to pass value from ajax to action?

I have a few checkboxes on my page. I have some jquery in place to ensure that only one checkbox is checked at a time. I have assigned a specific value to each checkbox. The below ajax finds the checkbox that is checked and I'm grabbing the value associated to it. How do I pass that value to my action?
AJAX
$("input:checkbox").click(function () {
var PaymentID = document.querySelector('#chkBox:checked').value;
alert(PaymentID); // for test
$.ajax({
type: "POST",
dataType: "json",
data: PaymentID,
contentType: "application/json; charset=utf-8",
url: "#Url.Action("MyAction", "Home")",
success: function () {
return PaymentID; // Failed attempt at passing data.
}
})
})
Action:
[HttpPost]
public ActionResult MyAction(string PaymentID)
{
// Magic
}
Please keep in mind i am fairly new to ajax. Thx guys.
You can pass a javascript object with name PaymentID ( same name as your action method parameter)
data: { PaymentID: PaymentID },
You do not need to specify contentType as you are sending a simply object. Also you do not necessarily need to specify dataType for your ajax call to send the data.
This should work.
var PaymentID = "some value";
$.ajax({
type: "POST",
data: { PaymentID: PaymentID },
url: "#Url.Action("MyAction", "Home")",
success: function (response) {
console.log('response', response);
}
});
Or you can use the $.post method.
$.post("#Url.Action("MyAction", "Home")",{ PaymentID: PaymentID }, function(response) {
console.log('response', response);
});

Passing multiple objects to my controller

I am passing an object to my controller like so:
var form = JSON.stringify({
"subRevisedRequest": $('#frmRevised').val(),
"subSubcontractor": $('#frmSubcontractor').val(),
"subDescription": $('#frmDesc').val(),
"subCostCode": $('#frmCostCode').val(),
"subAmt": $('#frmAmt').val(),
"subPaymentTerms": "terms",
"subRetainage": 10,
"subComments": $('#frmComment').val()
});
$.ajax({
url: '#Url.Action("CreateSubcontracts", "Routing")',
type: "POST",
datatype: "JSON",
contentType: "application/json; charset=utf-8",
data: form,
success: function(result) {
if (!result.success) {
$('#errormsg').empty();
$('#errormsg').append(result.message);
} else {
location.href = '#Url.Action("Index", "Home")';
}
},
error: function (result) {
alert("Failed");
}
});
my controller sees this as the object it is looking for:
public ActionResult CreateSubcontracts(RoutingSubcontracts s)
My problem is that I'd like to pass along just one more string. I know I can make a view specific model but I was wondering if I could do something like this for example:
public ActionResult CreateSubcontracts(RoutingSubcontracts s, string bu)
I have tried the the following with no luck:
data: JSON.stringify({ "s": form, "bu": "251" }),
but the complex object just comes through as null. Is there a way I can pass the object and a string through as well?
Try adding the string item in the JSON you already have. Dont stringify it or it will just send a big string that youll have to parse again on the server.
var form = {
"subRevisedRequest": $('#frmRevised').val(),
"subSubcontractor": $('#frmSubcontractor').val(),
"subDescription": $('#frmDesc').val(),
"subCostCode": $('#frmCostCode').val(),
"subAmt": $('#frmAmt').val(),
"subPaymentTerms": "terms",
"subRetainage": 10,
"subComments": $('#frmComment').val(),
"bu": "251" // add it here
};
$.ajax({
url: '#Url.Action("CreateSubcontracts", "Routing")',
type: "POST",
datatype: "JSON",
data: form,
success: function(result) {
if (!result.success) {
$('#errormsg').empty();
$('#errormsg').append(result.message);
} else {
location.href = '#Url.Action("Index", "Home")';
}
},
error: function (result) {
alert("Failed");
}
});
In your view jquery create a second var for bu. Assign the data in you ajax call like this;
data: { "s" : form, "bu" : "251" }
In your controller method change the signature to include a default value for bu like this;
public ActionResult CreateSubcontracts(RoutingSubcontracts s, string bu = "NoValue")
With the default value set bu will act like an optional parameter

How to call partial view through ajax in mvc3

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

Resources