How do we bind the data in kendo? - asp.net-mvc

function showCopy() {
var arr = [];
var data = $("#PlanDetailGrid").data("kendoGrid").dataSource.data();
for (var i >
= 0; i < data.length; i++) {
if (arr.indexOf(data[i].SessionName) === -1) {
arr.push(data[i].SessionName);
}
}

You can use this syntax
$('#PlanDetailGrid').data('kendoGrid').dataSource.data(result);//result is the data in json format
From the controller you can return the result as Json and bind it direclty using an ajax like
$.ajax({
type: "post",
datatype: "json",
contenttype: "application/json",
url: "/Controller/getResult",
success: function (result) {
if (result.Data.length > 0) {
$('#PlanDetailGrid').data('kendoGrid').dataSource.data(result.Data);
}
else {
$("#PlanDetailGrid").data("kendoGrid").dataSource.data([]);
}
}
});
in Controller
public ActionResult getResult([DataSourceRequest]DataSourceRequest request)
{
//get the result list
DataSourceResult result = lst.ToDataSourceResult(request);//lst is your resultant list
var jsonResult = Json(result, JsonRequestBehavior.AllowGet);
return jsonResult;
}

Related

JQuery ajax call blocks RedirectToAction

I have a view with an ajax call:
$.ajax({
url: "CreateChecklistCopies",
type: "POST",
data: JSON.stringify(drivers),
async: false,
contentType: "application/json; charset=utf-8",
});
The controller action performs some tasks and redirects to the index method of the controller:
[HttpPost]
public IActionResult CreateChecklistCopies([FromBody] object i_vm)
{
var tmp = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ChecklistCopyModel>>(i_vm.ToString());
int result = _obj.AddChecklistCopies(tmp);
if (result > 0)
return RedirectToAction("Index", new { SuccessMessage = "Checklists were successfully duplicated." });
else
return RedirectToAction("Index", new { ErrorMessage = "An error occurred when duplicating the checklist." });
}
The Index action is successfully executed but there's no forward to the index page happening:
[HttpGet]
public IActionResult Index(string FilterCreator, string salesPersonFilter, string SuccessMessage, string ErrorMessage)
{
if (FilterCreator == null)
{
FilterCreator = User.Identity.Name.Split("\\")[1];
}
else if (FilterCreator.ToLower() == "all")
{
FilterCreator = null;
}
var checklists = _obj.GetChecklists(true, FilterCreator, salesPersonFilter);
var salespersons = _obj.GetSalespersons();
var chlVm = _mapper.Map<List<ChecklistModel>, List<ChecklistListViewModel>>(checklists);
var ivm = new IndexViewModel
{
CheckLists = chlVm,
Salespersons = salespersons,
SuccessMessage = !string.IsNullOrEmpty(SuccessMessage) ? SuccessMessage : "",
ErrorMessage = !string.IsNullOrEmpty(ErrorMessage) ? ErrorMessage : ""
};
return View(ivm);
}
I played around with the async: false tag in the ajax call but that didn't help. Any ideas?
You cannot use RedirectToAction to action in an ajax call to redirect the entire page. Because the ajax response is limited to the ajax request scope only.
What you can do is return a json object instead of RedirectToAction like this:
[HttpPost]
public IActionResult CreateChecklistCopies([FromBody] object i_vm)
{
var tmp = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ChecklistCopyModel>>(i_vm.ToString());
int result = _obj.AddChecklistCopies(tmp);
JsonResult result = new JsonResult(new JsonSerializerSettings());
if (result > 0)
result = Json(new { IsRedirect = True, RedirectUrl = '/controller/Index/...', SuccessMessage = "Checklists were successfully duplicated." });
else
result = Json(new { IsRedirect = True, RedirectUrl = '/controller/Index/...', SuccessMessage = "An error occurred when duplicating the checklist." });
return result;
}
Then in the ajax call do this:
$.ajax({
url: "CreateChecklistCopies",
type: "POST",
data: JSON.stringify(drivers),
dataType: 'JSON',
async: false,
}).done(function (response) {
if (response != null) {
window.location = response.RedirectUrl;
//You can also use the IsRedirect and SuccessMessage property as needed
} else {
alert('There was a problem processing the request.');
}
}).fail(function () {
alert('There was a problem processing the request.');
});

Unable to send array data using ajax with ASP.NET Core and Entity Framework Core

I am trying to send array to the controller but it's blank in the controller parameter.
Ajax function is:
$('#pending').click(function () {
SaveTestResult("/Reception/PatientTests/SavePendingTest");
});
function SaveTestResult(url) {
var pid = $('.patientId').attr('id');
var tid = "";
var tval = "";
var tpid = "";
var tests = [];
$("table > tbody > tr").each(function () {
testId = $(this).find('.tid').val();
if (typeof (testId) != "undefined") {
tid = testId;
}
var rowText = ""
$(this).find('td').each(function () {
tpid = $(this).find('.tpId').val();
tval = $(this).find('.result').val();
if (typeof (tpid) != "undefined") {
tests.push({ PatientId: pid, TestId: tid, TestParameterId: tpid, TestValue: tval });
}
});
});
// alert(JSON.stringify(tests));
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(tests),
contentType: "application/json",
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
success: function (data) {
alert(data);
},
error: function (e) {
alert('Error' + JSON.stringify(e));
}
});
}
This is the controller method:
[HttpPost]
[Route("Reception/PatientTests/SavePendingTest")]
public async Task<IActionResult> SavePendingTest(List<PendingTestResult> pendingTestResult)
{
if (ModelState.IsValid)
{
foreach (PendingTestResult ptr in pendingTestResult)
{
_db.Add(ptr);
await _db.SaveChangesAsync();
}
// return new JsonResult("Index");
}
return new JsonResult(pendingTestResult); ;
}
But when run the code I see data array filled but inside of the SavePendingTest action, pendingTestResult is empty and not filled! I also tried the [FromBody] tag inside action params, but it does not work either!
Help me resolve this
you are sending a string with no names so the controller can not get the values.
change you code to
$.ajax({
type:"POST",
url:url,
data:test
...
});
the test should be an object not a string.
You can pass the list of objects by :
$.ajax({
type: "POST",
url: "Reception/PatientTests/SavePendingTest",
data: { pendingTestResult: tests },
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
success: function (data) {
alert(data);
},
error: function (e) {
alert('Error' + JSON.stringify(e));
}
});
pendingTestResult in data:{ pendingTestResult: tests } matches the parameter name on action and remove the contentType setting .

How to upload a Image in Asp.net MVC using Ajax request

How to upload a Image in Asp.net MVC using Ajax request I have single controller and its view file have to use Ajax request.
Index Controller
public ActionResult Index()
{
return View();
}
and its view
Textbox with id="imageUploadForm"
<input type="file" id="imageUploadForm" name="image" multiple="multiple" />
Ajax function
$(document).ready(function() {
$("#imageUploadForm").change(function() {
var formData = new FormData();
var totalFiles = document.getElementById("imageUploadForm").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("imageUploadForm").files[i];
formData.append("imageUploadForm", file);
}
$.ajax({
type: "POST",
url: '/Home/Upload',
data: formData,
dataType: 'json',
contentType: false,
processData: false
//success: function(response) {
// alert('succes!!');
//},
//error: function(error) {
// alert("errror");
//}
}).done(function() {
alert('success');
}.fail(function( xhr, status, errorThrown ) {
alert('fail');
};
});
});
Controller Function
[HttpPost]
public void Upload()
{
if(Request.Files.Count != 0){
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/"), fileName);
file.SaveAs(path);
}
}
}

Want to Save Posted Json data to database

I am posting JSON data through AJAX POST as ::
var length = $('.organizer-media').length;
var contents = $('.organizer-media');
var Title;
type == "New" ? Title = $('#newName').val() : Title = $('#Playlist option:selected').text();
var playlistid = $('#Playlist').val()
type == "New" ? playlistid = 0 : playlistid = $('#Playlist').val()
var data = [];
for (var i = 0; i < length; i++) {
data[i] = { ID: parseInt(contents[i].id), MetaID: parseInt(contents[i].title) }
}
var totaldata={ data: data, playlistid: parseInt(playlistid),Title:Title };
$.ajax({
type: 'POST',
data: JSON.Stringify(totaldata),
url: '/Builder/Save',
success: function () {
alert("Playlist saved successfully!!");
}
})
the JSON data is sent in following format::
{"data":[{"ID":779389,"MetaID":774367},{"ID":779390,"MetaID":774367},{"ID":779387,"MetaID":774366},{"ID":779388,"MetaID":774366},{"ID":779386,"MetaID":774365},{"ID":779385,"MetaID":774364},{"ID":779384,"MetaID":774363},{"ID":779383,"MetaID":774362},{"ID":779382,"MetaID":774361},{"ID":779381,"MetaID":774360},{"ID":779378,"MetaID":774359},{"ID":779379,"MetaID":774359},{"ID":779377,"MetaID":774358},{"ID":779376,"MetaID":774357},{"ID":779375,"MetaID":774356},{"ID":779372,"MetaID":774355},{"ID":779373,"MetaID":774355},{"ID":779374,"MetaID":774354},{"ID":779370,"MetaID":774353},{"ID":779394,"MetaID":774370}],"playlistid":1461,"Title":"MX OPEN TALENT MARIA"}:
and as I made an ItemViewModel as ::
public class ItemEditViewModel
{
public long ID { get; set; }
public long MetaID { get; set; }
}
and My controller code is as::
[HttpPost]
public ActionResult Save(ItemEditViewModel[] data,long playlistid=0, string Title="")
{
for (int i = 0; i < data.Length; i++)
{
var pc = db.PlaylistContents.FirstOrDefault(x => x.PlaylistContentId == data[i].ID);
if (pc == null)
{
pc = new PlaylistContent();
db.PlaylistContents.Add(pc);
}
pc.ContentMetaDataId = data[i].MetaID;
pc.PlaylistContentSequenceId = i + 1;
}
db.SaveChanges();
return Json(new { foo = "bar", baz = "Blech" });
}
while Execution of data in controller it doesn't accept the POSTED data as its ViewModel values.
My Problem is solved.
As I have Posted array in combination with two other variables, I just need to stringify array & not the whole ajax data which is to be posted.
as you can see in my code below::
var totaldata = { data: data, playlistid: parseInt(playlistid), Title: Title };
$.ajax({
type: 'POST',
data: { data: JSON.stringify(data), playlistid: parseInt(playlistid), Title: Title, deleted: JSON.stringify(deleted) },
traditional:true,
url: 'Save',
success: function (data) {
alert("Playlist saved successfully!!");
}
})
In above code I have just done stringify on array & not on other data.
Thanks for some Co-operations of yours.

observableArray sent as parameter to a contoller function is null

I want to pass the data in the FeatureList (observableArray) to the SaveMappings function in the TreeController. I have binded a button to the sendItems function. I put a breakpoint at the var data=p2fData line to see what I received. p2fData is null.
I changed the controller to public JsonResult SaveMappings(List p2fData). In this case p2f data shows that there is 1 element, but then its null too.
var Feature = function (featId) {
var self = this;
self.featId = featId;
self.parameters = ko.observableArray();
}
var ParameterToFeatureListViewModel = function () {
var self = this;
var newFeature = new Feature("Feature XYZ");
newFeature.parameters.push("1");
newFeature.parameters.push("2");
self.FeatureList = ko.observableArray([newFeature]);
self.sendItems = function() {
$.ajax({
type: "POST",
url: '/Tree/SaveMappings',
data: ko.toJSON(self.FeatureList),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response);
},
error: function (request, status, error) {
alert(request.statusText);
}
});
}
}
var vm = new ParameterToFeatureListViewModel()
ko.applyBindings(vm);
public class TreeController:Controller
{
public ActionResult Index(){...}
[HttpPost]
public JsonResult SaveMappings(string p2fData)
{
var data = p2fData;
return Json(data);
}
}
Please have a look # how to pass knockoutjs view model into a mvc controller
... May be it helps..

Resources