I am trying to refresh a Kendo UI grid but have not yet been successful. Would anybody please advise what I missed or what I did wrong?
I have the following code:
.cshtml:
$('#btnRefresh').click(function (e){
$.ajax({
type: 'POST',
url: "#(Url.Content("~/Administration/RefreshAll/"))",
success: function () {
$("#Product").data("kendoGrid").dataSource.read();
$('#Product').data('kendoGrid').refresh();
//grid.refresh();
location.reload(true);
},
error: function (){
$("#btnRefresh").removeAttr('disabled');
}
});
});
Controller:
public ActionResult RefreshAll([DataSourceRequest] DataSourceRequest request)
{
db.ProcessAll();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
return View();
}
your script should be
$('#btnRefresh').click(function (e){
var grid = $("#Product").data("kendoGrid");
grid.dataSource.page(1);
grid.dataSource.read();
});
in your controller add references to
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;
your ActionResult should be
public ActionResult RefreshAll([DataSourceRequest] DataSourceRequest request)
{
//assuming db.ProcessAll() will return a list object
return Json(db.ProcessAll().ToDataSourceResult(request));
}
Related
I am working on cascaded dropdownlist with data passed with dataview.
Controller:
public ActionResult Index()
{
ViewBag.States = new SelectList(db.PLStates, "PLStateID", "PLStateName");
ViewBag.Cities = new SelectList(db.PLCitys, "PLCityID", "PLCityName");
return View();
}
[HttpPost]
public JsonResult GetCity(int SelectedStateId)
{
SelectList result = new SelectList(db.PLCitys.Where(x => x.PLStateID == 3), "PLCityID", "PLCityName");
return Json(result);
//return Json(ViewBag.Cities = new SelectList(db.PLCitys.Where(x => x.PLStateID == 3), "PLCityID", "PLCityName"));
}
HTML:
<script type="text/javascript">
$(document).ready(function () {
$("#States").change(function () {
var SelCity1 = $("#States").val();
$("#Cities").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetCity")',
dataType: 'JSON',
data: { SelectedStateId: SelCity1 },
success: function (Cities) {
ViewBag.Cities = Cities;
$("#Cities").append('Cities');
alert("success" + Cities);
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
<div>
#Html.DropDownList("States", "Select one")
#Html.DropDownList("Cities", "Select one")
</div>
In alert i can see the json gives back objects but the Cities dropdownlist becomes emptied with no value inside. Why ddl.cities is not filled with retured values??
Additional question is how to add style to dropdownlist??
You will have to manually add options to the cities drop down via js with the Json data returned from the controller.
As far as styling. You can style in inline by adding a "style"= to the html attributes or style with external css class using the #class html attribute.
I am new in MVC. I have a DropDown in index view and i want to show entire table basis on selected item from dropdown. I fire ajax on onChange function of dropdown using jQuery.
$(document).ready(function () {
$("#ddlUser").change(function () {
$("#ddl2").empty();
$.ajax({
type: "POST",
url: '#Url.Action("getState")',
dataType: "json",
data: { id: $("#ddlUser").val() },
success: function (city) {
},
error: function (ex) {
alert('failed to retrieve' + ex);
}
})
});
return false;
});
and i get data from database using this code
public JsonResult getState(int id)
{
MvcDemo9Feb.Models.ModelData MD = new Models.ModelData(); //MD is object of model and dt is DataTable type property
MD.dt = obDB.getCity(id);//obDB is class and getCity is method of it that return datatable
return Json(MD);
}
here i don't know how to bind data of model object MD to table on view. Please suggest something
I want to send a complex object from my view (via Ajax) to my controller. I know that I can do something like:
JSON.stringify(myComplexObject);
and then retrieve values in the controller. But is this really the best way to do it? I'm thinking some sort of data contract between view and controller would be better?
you can use the following
#using(Html.BeginForm("YourAction","YourController",FormMethod.Post))
{
....
}
<script>
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
alert('Ok');
}
});
}
return false;
});
});
</script>
and in your Controller
public ActionResult YourAction(YourModel model)
{
}
hope this will help you
I am loading a PartialView into a Jquery UI dialog and if something went wrong during the post method I reload the PartialView into the dialog again ( ModelState errors for example ) . At this point my ajax sumbit doesn't work anymore. It justs redirect me and it should not.
What is wrong in my code ? Here is what I have tried :
$('#editdialog').dialog({
autoOpen: false,
width: '900px',
modal: true,
open: function (event, ui) {
$(this).load('Controller action', function (html) {
$('#incarcerationForm').submit(function () {
$.ajax({
url: 'Controller action',
data: $("#myForm").serialize(),
type: "POST",
success: function (data) {
$('#editdialog').html(data);
$.validator.unobtrusive.parse($("#myForm"));
if ($("#myForm").valid()) {
GetDetails(#Model.FormModel.ID);
$('#editdialog').dialog('close');
console.log("myForm was edited successfully");
return false;
}
return false;
},
error: function (data) {
$('#editdialog').html(data);
console.log("error at edit myForm");
return false;
}
});
return false;
});
return false;
});
}
});
And my [HttpPost] Controller action :
public ActionResult Create(Mymodel viewModel)
{
return CheckValidBusiness(() =>
{
viewModel.Save(viewModel.FormModel); return true;
})
.Valid(() => PartialView(viewModel))
.Invalid(() => PartialView(viewModel));
}
Replace:
$('#incarcerationForm').submit(function () {
with:
$(document).on('submit', '#incarcerationForm', function () {
so that you subscribe to the submit event of the form in a lively manner which will be resilient to DOM changes. Take a look at the .on() method for more information.
The situation, I'm making multiple ajax/json requests on the same page to a controller, which returns a JsonResult.
I know this is a problem with the session state, I've added the [SessionState(SessionStateBehavior.Disabled)] attribute on my controller class, but nothing seems to work, my second ajax request just wont get the return data.
the controller:
[SessionState(SessionStateBehavior.Disabled)]
public class IndexController : Controller
{}
the two json methods:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetLatestListJSON()
{
Thread.Sleep(5000);
ArticleRepository repo = new ArticleRepository();
IList<ArticleModel> list = repo.GetLatestContent(10);
return Json(list, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetCustomerJSON()
{
Thread.Sleep(5000);
CustomerRepository Repo = new CustomerRepository();
IList<Customer> cust= Repo.GetCustomer();
return Json(cust, JsonRequestBehavior.AllowGet);
}
The second ajax call, the other one is very similar, I never get to see the 'succes'-alert.
<script type="text/javascript">
$(document).ready(function () {
alert('before');
$.getJSON("/Index/GetCustomerJSON", null, function (data) {
alert('succes');
$("#loadingGifVideo").hide();
$.each(data, function (index, mod) {
});
});
});
Thanks guys :)
If you put a break-point in your GetCustomerJSON method and run this in Visual Studio does the method ever get called? It does
EDIT
Try switching from getJSON to the ajax method so you can capture any errors. Like so:
$.ajax({
url: "/Index/GetCustomerJSON",
dataType: 'json',
data: null,
success: function (data) { alert('success'); }
error: function (data) { alert('error'); }
});
Do you get an "error" alert?