I have a PartialView which renders a Grid using a List of Model Class passed from the controller.
#model IEnumerable<DeliveryDashboard.Models.UpcomingDMR>
#Html.Partial("~/Views/Shared/_DMRGrid.cshtml", Model)
The Grid Renders perfectly. Now I have added a Drop down at the top of the Grid.
in the OnChange event of the Drop down, I need to hit the controller and get an Updated list of Same Model Class which should refresh the existing Grid.
<script type="text/javascript">
$(function () {
//Refresh Grid on Date Range Change
$('#DateRange').change(function () {
$.ajax({
url: '#Url.Content("~/DMR/UpcomingDMRByDateRange/")',
dataType: 'json',
type: 'POST',
data: JSON.stringify({ DateRange: $('#DateRange option:selected').val() }),
contentType: 'application/json',
success: function (result) {
// Refresh partialView Here
}
});
});
});
My controller code returns the List of Model Class which I need to use to bind the Partial View.
public List<UpcomingDMR> UpcomingDMRByDateRange(string DateRange)
{
// get data from database and prepare List<UpcomingDMR>
return NewDataList;
}
Now How can I refresh my partial View from the Success block of my Ajax Call ?
You can do it like this in your success method :
$(function () {
//Refresh Grid on Date Range Change
$('#DateRange').change(function () {
$.ajax({
url: '#Url.Content("~/DMR/UpcomingDMRByDateRange/")',
dataType: 'json',
type: 'POST',
data: JSON.stringify({ DateRange: $('#DateRange option:selected').val() }),
contentType: 'application/json',
success: function (result) {
$("#your_partial_view_id").load('#Url.Action("Foo","Bar")',result)
}
});
});
});
Related
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);
});
I am trying to send a list of ids of checkboxes selected every time the user clicks on a checkbox. This will be used for search results to be filtered by categories. I don’t know if this is the correct way to do it but this is what I have tried so far.
This is my partial view with ajax call:
#using GAPT.Models
#model ViewModelLookUp
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#selectedcategories").click(function () {
var array = [];
if ($(this).is(":checked")) {
array.push($(this).val());
}
else {
array.pop($(this).val());
}
$.ajax({
type: "POST",
url: '#Url.Action("SearchTours", "Home")',
dataType: "html",
traditional: true,
data: { values: array },
success: function (data) {
$('#selectedcategories').html(data);
}
});
});
});
</script>
#using (Html.BeginForm("SearchCategories", "Home", FormMethod.Post))
{
foreach (var category in Model.categories)
{
<div class="checkbox" id="#{#category.Id}">
<label>
<input type="checkbox" id="selectedcategories" name="selectedcategories" value="#{#category.Id}"/>#category.Name
</label>
</div>
}
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
And this is my controller method that I am trying to reach:
[HttpPost]
public ActionResult SearchTours(FormCollection collection)
{
// insert query here
ViewData["CategAttrTours"] = CategAttrTours;
return View(CategAttrTours);
}
The method in the controller is not being reached and I am getting this error:
Error
Do you have any idea why I keep getting this error? Is it because I am passing the data incorrectly?
I would appreciate any help. Thanks a lot.
You need to add the contentType option and stringify your data
$.ajax({
type: "POST",
url: '#Url.Action("SearchTours", "Home")',
dataType: "html",
contentType: "application/json; charset=utf-8", //add this
data: JSON.stringify({ values: array }), // modify this
data: { values: array },
success: function (data) {
$('#selectedcategories').html(data);
}
});
and change you method to (assumes category.Id is typeof int)
[HttpPost]
public ActionResult SearchTours(IEnumerable<int> values)
although your script to generate the array is unnecessary and you can just use
$.ajax({
type: "POST",
url: '#Url.Action("SearchTours", "Home")',
dataType: "html",
data: $('form').serialize(),
success: function (data) {
$('#selectedcategories').html(data);
}
});
or more simply
$.post('#Url.Action("SearchTours", "Home")', $('form').serialize(), function(data) {
$('#selectedcategories').html(data);
});
and change the method to
[HttpPost]
public ActionResult SearchTours(IEnumerable<int> selectedcategories)
Side note: You should never need to use FormCollection in MVC
remove this
dataType: "html"
traditional: true
on controller method parameter change this
(FormCollection collection)
to
List<string> values
place a break point on the controller and check the values
html part
<input data-bind="kendoComboBox: { dataTextField: 'FirstName', dataValueField: 'PersonID', data: AllUsers,template: '<span>#= data.FirstName # #= data.LastName # </span>', value: SelectedUserID,
change: UserSelectionChanged}" />
event handler inside model
var self= this;...
self.UserSelectionChanged = function () {
$.ajax({
type: "POST",
url: defaultUri + '/Home/GetUserTasks',
data: JSON.stringify({ PersonID: self.SelectedUserID() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (o) {
self.SelectedUserTask(null);
self.SelectedUserTask(o);
//RRM: Added this line below so that whenever user dropdown is changed or refresh button is clicked in AssignedTo the first task of that particular user is Selected.
self.selectTask(o[0]);
}
});
};
here the event is being called but the data in self is not there. The event doesn't seems to be bind well with knockout.
how to properly bind the ko event in the kendo combobox event?
Instead of registring to the change event, I'd subscribe to SelectedUserID:
var self= this;
...
self.SelectedUserID.subscribe(function(selectedUserId) {
$.ajax({
type: "POST",
url: defaultUri + '/Home/GetUserTasks',
data: JSON.stringify({ PersonID: selectedUserId }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (o) {
self.SelectedUserTask(null);
self.SelectedUserTask(o);
//RRM: Added this line below so that whenever user dropdown is changed or refresh button is clicked in AssignedTo the first task of that particular user is Selected.
self.selectTask(o[0]);
}
});
});
This way it doesn't matter when or how the SelectedUserID is being changed.
As sroes wrote subscribing to the observable is the best choice here.
In cases where you have to bind to the kendo event then you can do this:
data-bind="... change: UserSelectionChanged(), ...."
Notice the function call parenthesis at the end ^
Now you function has to be like this:
this.UserSelectionChanged = function () {
var self = this;
return function(e) {
$.ajax({
self.blah ...
});
}
}
Now you have created a closure and you can access your view model using self but you also have the original Telerik event args inside e like e.dataItem etc.
So now you are unstoppable, you can do everything!
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);
}
});
});
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.