Async file upload in MVC using kendoUpload - asp.net-mvc

I am using file uploader with MVC.
Following is my code :
<div class="demo-section k-content">
<input name="files" id="files" type="file" />
</div>
<script>
$(document).ready(function () {
var data = JSON.stringify({
'ReportID': '#(Model.ReportID)',
});
$("#files").kendoUpload({
async: {
saveUrl: '#Url.Action("save", "UserPage")',
//removeUrl: "remove",
autoUpload: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: data,
}//,
});
});
on ActionResult I am using following code :
string fileName = Path.GetFileName(files.FileName);
fileName = model.ReportID + "s" + Guid.NewGuid() + extension;
Everything is working fine except the value of model.ReportID its returning NULL every time.
I am missing something here?

Try something like that:
#(Html.Kendo().Upload()
.Name("uploadFiles")
.Async(a => a
.Save("Save", "Upload")
.Remove("Remove", "Upload")
.AutoUpload(true)
.SaveField("files")
//.Batch(true)
.RemoveField("fileNames")
)
.Multiple(true)
.ShowFileList(true)
.Events(events => events
.Error("onUploadError")
.Progress("onUploadProgress")
.Complete("onUploadComplete")
.Success("onUploadSuccess")
.Select("onUploadSelect")
.Upload("onUploadAdditionalData")
.Remove("onUploadRemove"))
)
inside the onUploadAdditionalData event you can pass parameters like:
function onUploadAdditionalData(e) {
e.data = { val1: val1, val2: val2 };
}
your controller action should look like this:
public ActionResult Save(IEnumerable<HttpPostedFileBase> files, string val1, string val2)
{
//do upload handling here
}

If you check documentation http://docs.telerik.com/kendo-ui/api/javascript/ui/upload#configuration-async async.data is undocumented and i am not sure if there is such property.
You can put it directly to saveUrl:
saveUrl: '#Url.Action("save", "UserPage", new { ReportID = Model.ReportID })'

Related

render MVC view with json data

I have a method that return json data to my mvc view, not sure why my view shows json data instead of what I have in success part. This is my Post method:
[HttpPost]
[Route("resetpassword")]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel resetPasswordViewModel)
{
...
if (ModelState.IsValid)
{
if (resetPasswordViewModel.Password == resetPasswordViewModel.ConfirmPassword)
{
var user = Task.Run(() => Service.GetUserByEmailAsync(email)).Result;
if (user != null)
{
userRequest.Id = user.FirstOrDefault().Id;
userRequest.Password = resetPasswordViewModel.Password;
userRequest.Token = token;
await Service.UpdateUserAsync(userRequest);
}
}
else
{
return Json(new { status = "error", message = "Please enter the same value again" });
}
}
return Json(new { status = "success", message = "" });
}
This is my view that is modal:
#model Models.ResetPasswordViewModel
#if (Model != null)
{
<div class="page resetPassword">
#using (Html.BeginForm("resetpassword", "Home", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="modal" id="reset-password">
<div class="modal-content">
<span class="close">X</span>
<div><input type="email" name="email" id="email" readonly value=#Model.Email /></div>
<div class="create-user-label">Password</div>
....
and this is my ajax function:
function resetPassword() {
var postResult = null;
var data = {
Email: document.getElementById('email').value
};
var path = "/resetpassword";
var errorMessage = document.getElementById('Message');
$.ajax({
dataType: "json",
contentType: "text/plain",
url: path,
type: "POST",
cache: false,
data: data,
success: function (result) {
postResult = $.parseJSON(result);
alert(postResult.data);
if (result && result.message) {
$('#reset-password').hide();
$('#reset-thank-you').show();
}
},
error: function () { alert("error"); }
});
}
but instead of my view I only see json data in my screen like:
{"status":"success","message":""}
Your data will be automatically converted from JSON format into Javascript objects.
Presumably you just want to display the message in an alert:
success: function (result)
{
alert(result.data.message);
},
Well your data is going through, looks like you have some mapping problems, you should try this.
$.ajax({
dataType: "json",
contentType: "text/plain",
url: path,
type: "POST",
cache: false,
data: data,
success: function (result) {
alert(result['status']);
if (result['status']== 'success') {
$('#reset-password').hide();
$('#reset-thank-you').show();
}
},
error: function () { alert("error"); }
});

Ajax refresh in mvc div data

I am developing a MVC application, where I have a scenario to refresh a part of the page basically ajax...
<div id="ajax" style="width:10%;float:left">
#foreach (var item in #Model.SModel.Where(x=>x.StudentId==13))
{
<li>#Html.DisplayFor(score => item.StudentName)</li>
}
This is the div (part of the page) which I need to refresh on a button click. I have 2 js files, data.js and render.js...
data.js contains a template as follows:
makeAJAXCall =
function (url, params, callback) {
$.ajax({
type: "get",
timeout: 180000,
cache: false,
url: url,
dataType: "json",
data: params,
contentType: "application/json; charset=utf-8",
success: function (result) {
if (callback) {
callback(result);
}
},
error: function (req, status, error) {
}
return null;
}
});
};
getGrid = function () {
makeAJAXCall(urlCollection["getGridInfo"], "", function (result) {
renderer.renderGridInfo('ajax', result);
});
};
and render.js file is as follows:
renderGridInfo = function (area, data) {
$("#" + area).text(data);
};
return {
renderGridInfo: renderGridInfo
};
In the loading page on button click function as :
Service.addURL('getGridInfo', '#Html.Raw(#Url.Action("getGridInfo", "AjaxController"))');
Service.getGrid();
In the ajax controller, the code is :
public JsonResult getGridInfo()
{
return Json(model, JsonRequestBehavior.AllowGet);
}
But the problem I am facing is, the controller is returning the JsonResult , but the 'div' accepts the model and so the output is [object] [object] button click
Question: Is there any way to refresh this 'div' from the Jsondata returned by the controller?
I have to follow this type of design without using AjaxForm.
Look what happens:
1) you returns Json: return Json(model, JsonRequestBehavior.AllowGet);
2) you put returned Json object to the div's value: $("#" + area).text(data);
that's why you end up with json's representation inside div
You need to change it as follows:
1) assume you put html for that div to model's field called NewHtml
2) eptract html from the property of returned json: var returnedHtml = data.NewHtml;
3) use html() method instead of text(): $("#" + area).html(returnedHtml);

Populating a Webgrid from an Ajax Call

I have a problem with populating a Webgrid from an Ajax call.
I have followed the example as showed in the following thread: mvc3 populating bind webgrid from ajax however, that did not yield any results.
When I run the website, I always get the message: "Error: undefined".
when debugging the code, I am quite sure that the problem lies in the fact that the return PartialView is the problem, as my data object in the ajax success method does not get filled with data.
Here are the examples of my code:
Ajax call:
$.fn.getCardResult = function (leerling, kaart) {
$.ajax({
type: "GET",
url: '#Url.Action("GetResults","Kaarten")',
data: { leerlingID: leerling, cardID: kaart },
cache: false,
success: function (data) {
console.log(data);
if (!data.ok) {
window.alert(' error : ' + data.message);
}
else {
$('#card').html(data);
}
}
});
}
Partial View call:
<div class="card-content" id="card">
#{
if(Model.Kaart != null && Model.Kaart.Count > 0)
{
#Html.Partial("_Kaarten")
}
else
{
#: Er zijn geen kaarten beschikbaar.
}
}
</div>
Partial View:
#model List<ProjectCarrousel.Models.KaartenModel>
#{
var grid = new WebGrid(source: Model,ajaxUpdateContainerId: "card",
defaultSort: "Topicname");
grid.GetHtml(
tableStyle: "webgrid",
columns: grid.Columns(
grid.Column("Topicname", "Topic"),
grid.Column("Taskname", "Taken"),
grid.Column("Taskpoints", "Punten"),
grid.Column("Grades", "Resultaat"),
grid.Column("Date", "Datum"),
grid.Column("Teachercode", "Paraaf Docent")
)
);
}
Controller code:
public ActionResult GetResults(int leerlingID, string cardID)
{
try
{
int Ovnumber = leerlingID;
string CardId = cardID;
List<KaartenModel> kaartlijst = new List<KaartenModel>();
IEnumerable<topic> topics = _db.topic.Include("tasks.studenttotask").Where(i => i.CardID == CardId);
foreach (topic topic in topics)
{
foreach (tasks task in topic.tasks)
{
KaartenModel ka = new KaartenModel();
ka.Topicname = task.topic.Topicname;
ka.Taskname = task.Taskname;
ka.Taskpoints = task.Taskpoints;
ka.Ranks = task.Ranks;
ka.Date = task.studenttotask.Where(i => i.Ovnumber == Ovnumber).Select(d => d.Date).SingleOrDefault();
ka.Grades = task.studenttotask.Where(i => i.Ovnumber == Ovnumber).Select(d => d.Grades).SingleOrDefault();
ka.Teachercode = task.studenttotask.Where(i => i.Ovnumber == Ovnumber).Select(d => d.Teachercode).SingleOrDefault();
kaartlijst.Add(ka);
}
}
KVM.Kaart = kaartlijst;
return PartialView("_Kaarten", KVM.Kaart);
}
catch (Exception ex)
{
return Json(new { ok = false, message = ex.Message });
}
}
If anyone could help it would be greatly appreciated.
UPDATE
After fiddling about a bit I found a solution that worked for me. Below is a snippet of an updated Ajax Call:
The solution I found was too make the Success method in another way. This made sure that the Partial View rendered properly. Below is the Ajax call snippet.
$.ajax({
url: '#Url.Action("GetAjaxCall","Home")',
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html',
data: { id: id },
})
.success(function (result) {
$('#sectionContents').html(result);
})
.error(function (xhr, status) {
alert(xhr.responseText);
});
The solution I found was too make the Success method in another way. This made sure that the Partial View rendered properly. Below is the Ajax call snippet.
$.ajax({
url: '#Url.Action("GetAjaxCall","Home")',
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html',
data: { id: id },
})
.success(function (result) {
$('#sectionContents').html(result);
})
.error(function (xhr, status) {
alert(xhr.responseText);
});

dropdownlistfor selected value list item possible?

I'm currently working in ASP.NET MVC 4 and I'm trying to do something special here.
Here's the code I currently have for my dropdownlist:
#Html.DropDownListFor(m => m.SourceList, new SelectList(Model.SourceList, "Id", "Name", new { id = "SourceList" }))
Now this works, but it's pretty dumb what I'm doing here. In my back-end I query again to get the entire model from the id I just selected.
What I need is not the Id of the selected model, but the entire model. Is there any way of doing this?
My current JQuery callback:
$.ajax({
url: '#Url.Action("SetLicensesAfterSourceChange", "Permission")',
type: 'POST',
dataType: 'json',
contentType: 'application/json;',
data: JSON.stringify({ "Id" : selectedStartSourceId, "sourceList" : jsonSourceList }),
success: function (result) {
//Do stuff here
}
});
What I want to be able to do:
$.ajax({
url: '#Url.Action("SetLicensesAfterSourceChange", "Permission")',
type: 'POST',
dataType: 'json',
contentType: 'application/json;',
data: "selectedModel" = modelFromDropDownList,
success: function (result) {
//Do stuff here
}
});
It's probably a bit far-fetched, but you could create a Javascript array representation of your entire list of source objects, and use jQuery and a simple html select ( with the id & name for the options) to retrieve the item from the array.
<script>
var items = [
{
name = "een",
value = "1",
propertyX = "hallo"
},
{
name = "twee",
value = "2",
propertyX = "wereld"
}
];
$("#ddlselect").change(function(e) {
e.preventDefault();
var selectedOptionVal = $(this).val();
var found = null;
foreach (item in items)
{
if (!found && item.value == selectedOptionVal)
found = item;
}
// use found if set
if (found)
{
}
});
</script>
<select id="ddlselect">
<option value="">-- kies --</option>
<option value="1">een</option>
<option value="2">twee</option>
</select>

how do I get the form data in a javascript object so I can send it as the data parameter of an $.ajax call

How to return json after form.submit()?
<form id="NotificationForm" action="<%=Url.Action("Edit",new{Action="Edit"}) %>" method="post" enctype="multipart/form-data" onsubmit='getJsonRequestAfterSubmittingForm(this); return false;'>
<%Html.RenderPartial("IndexDetails", Model);%>
</form>
$.ajax({
url: '<%=Url.Action("Edit","Notification") %>',
type: "POST",
dataType: 'json',
data: $("#NotificationForm").submit(),
contentType: "application/json; charset=utf-8",
success: function(result) {
if (result.Result == true) {
alert("ghjghsgd");
}
},
error: function(request, status, error) {
$("#NotSelectedList").html("Error: " & request.responseText);
}
});
I guess what you're actually looking for is not the Submit method, but how to serialise the form data to a json object. To do this you have to use a helper method like here: Serialize form to JSON
Use this instead of running the submit() method, and you'll be fine.
Also, this question is a duplicate of this (even though the question text, and the title are completely misleading): Serialize form to JSON with jQuery
Posting the jQuery extender, just in case, so that it doesn't get lost :)
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
After you have this in your page, you can update your ajax call with this:
$.ajax({
url: '<%=Url.Action("Edit","Notification") %>',
type: "POST",
dataType: 'json',
data: $("#NotificationForm").serializeObject(),
contentType: "application/json; charset=utf-8",
success: function(result) {
if (result.Result == true) {
alert("ghjghsgd");
}
},
error: function(request, status, error) {
$("#NotSelectedList").html("Error: " & request.responseText);
}
});
UPD: If you want to POST the form, then get the response as a json object, and do another ajax call.. then you should look at the jquery.form plugin. you will be able to post your form using an ajax call, then get the response, and run some js when it will return.

Resources