KendoUpload FileUpload httppostedfile not working on submit - asp.net-mvc

I am using #(Html.Kendo().Upload() in my app. I have to take the top 5 records from csv and bind it to kendo grid in javascript. I'm reading the file info from httppostedfilebase and returning the top 5 records as JSON result in save action method. On Upload success in javascript i'm binding the grid.
Now on submit, i have to read the file again. i'm trying to read the file information from httppostedfilebase but it is null because the save action method returns JSON. If i change the save action method to view, i'm ablet o read the httpostedfilebase on submit.
Is there a workaround?
Thanks!

Code Sample:
view
----
#(Html.Kendo().Upload()
.Name("uploadTemplate")
.Messages(m => m.Select(""))
.ShowFileList(true)
.Async(a => a
.Save("UploadData", "Lead")
.AutoUpload(true)
)
.Multiple(false)
.Events(events => events
.Select(UploadFileControl.onSelect")
.Success("UploadFileControl.onSuccess")
.Upload("UploadFileControl.onUpload")
)
)
form
----
#using (Html.BeginForm("", "", FormMethod.Post, new { id = "LoadForm", enctype = "multipart/form-data" }))
js
--
function SubmitForm(val) {
var url = '#Url.Action("fileSubmit", Test")';
console.log(url);
$.ajax({
url: url,
type: 'POST',
data: $('form#LoadForm').serialize(),
async: false,
success: function (data) {
alert("success");
},
error: function (data, xhr, error) {
alert("error");
}
});
}
onSuccess(e)
{ var grid = $("#grid").data("kendoGrid");
var origData = e.response;
grid.dataSource.data(origData);
}
document ready
--------------
var grid = $("#grid").kendoGrid({
groupable: false,
scrollable: true,
columnMenu: true
}).data("kendoGrid");
code behind
-----------
public JsonResult UploadData(IEnumerable<HttpPostedFileBase> uploadTemplate, FileModel fileModel)
{
Stream inputFileStream = new MemoryStream();
string[] result = new string[] { };
if (uploadOnly)
{
if (uploadTemplate != null)
{
try
{
foreach (var file in uploadTemplate)
{
inputFileStream = file.InputStream;
}
// GET TOP N ROWS AND ASSIGN TO parentRow
return Json(parentRow, JsonRequestBehavior.AllowGet);
}
return null;
}
public ActionResult fileSubmit(IEnumerable<HttpPostedFileBase> uploadTemplate, FileModel fileModel)
{
//retrieve uploadTemplate here (no values in uploadTemplate.)
}

Related

How to pass JSON data (list created using Jquery) to an action in controller in MVC?

I have a function in jquery which creates a list of values being selected from a checkbox. Now I want to have this list in my controller action. I have converted this list to JSON but I am not able to pass it to the controller. I also tried creating a custom model corresponding to the json data.
Jquery Code
$("button").click(function () {
//alert("clicked");
var obj = {};
//var tempRadio = [];
for (var i = 1; i <= globalVar; i++) {
if ($("#" + i).prop("checked") == true) {
obj[i] = $('input[class=' + i + ']:checked').val();
}
}
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '#Url.Action("SkillAdd","User")',
data: JSON.stringify(obj),
//data: hello,
error:function ()
{
alert("Error");
},
success: function () {
alert(JSON.stringify(obj));
}
});
});
Controller Code
public ActionResult SkillAdd(List<string> Id, List<string> Name)
{
return View();
}
Controller Code with Custom Model
public ActionResult SkillAdd(List<MyModel> object)
{
return View();
}
You have an object in javascript but you need to create an array so that it can be mapped to List at post. So change your js code to be :
var obj = []; // it's array now
and then you will add items in it like in your loop:
obj.push( $('input[class=' + i + ']:checked').val());
and in your ajax call name the parameter what you have in your controller action:
data:{ Id : obj }
and now you can have a parameter in action method List<string> which would hold the data posted by ajax call.
public ActionResult SkillAdd(List<string> Id)
{
return View();
}
Hope it helps.

how to set selected values to a multi select dropdown list on form load in .net mvc

I am using a multi select dropdown for a particular entry, which is retrieved from a table. If I am trying to edit this entry the selected dropdown is not showing.
This is my script.
<script type="text/javascript">
$(document).ready(function () {
//$('#Supplier').click(function () {
var sku = $("#SKU").val();
alert(sku);
//var pay = null;
//alert(suppid);
$.ajax({
url: '/SKUMasterSetup/supplierlist',
type: 'POST',
dataType: 'json',
data: { id: sku },
success: function (Supplierdata) {
alert("hi");
alert(Supplierdata);
var x = Supplierdata.length();
alert(x);
//<option value="{$T.data.Value}">{$T.data.Text}</option>
//for (var i = 0; i < Supplierdata.length; i++) {
// $("#supplier").append("Selected", Supplierdata[i], "selected").attr('selected', true);
for (var i in Supplierdata) {
var optionVal = Supplierdata[i];
$("#supplier").find("option[value=" + optionVal + "]").prop("selected", "selected");
}
// $('.class1').append("<option>" + "Please select" + "</option>");
},
//error : function (Supplier) { alert("Error !"); };
});
});
</script>
And my controller code is:
[HttpPost]
public JsonResult supplierlist(int id)
{
var Supplierdata = (from item in db.SupplierSKUMaps
where item.SKU == id
select item.SupplierMaster.SupplierName).ToList();
return Json(Supplierdata, JsonRequestBehavior.AllowGet);
}
And my dropdownlist is:
#Html.DropDownList("Supplier", ViewBag.Supplier as MultiSelectList, new { #class = "chosen", #id="supplier", #multiple = "multiple" })
you could always use #Value = #Html.Action(getMyFields) and within your controller, place an action method that returns Content result(MyData.ToList()).
More information on creating dropdowns can be found here: http://odetocode.com/blogs/scott/archive/2013/03/11/dropdownlistfor-with-asp-net-mvc.aspx

MVC: Result from JSON Automatically fill View

I am stuck in publishing the result from JSON so left the success portion blank.
View
#model MvcApplication2.Models.About
#{
ViewBag.Title = "About";
}
<p> #Html.DisplayFor(m=>m.test) </p>
<p> #Html.DisplayFor(m=>m.test1) </p>
Model
public class About
{
public string test { get; set; }
public string test1 { get; set; }
}
Controller
public class HomeController : Controller
{
public JsonResult About()
{
ViewBag.Message = "Your app description page.";
About ab = new About()
{
test = "a",
test1 = "b"
};
return Json(ab, JsonRequestBehavior.AllowGet);
}
}
JQuery in external file
$(document).ready(function () {
var itemName = "#btn-about";
$(itemName).click(function () {
$.ajax({
type: 'GET',
dataType: 'Json',
url: '/Home/About',
success: function (data) {
var option = '';
},
error: function (xhr, ajaxOption, thorwnError) {
console.log("Error")
},
processData: false,
async: true
});
});
});
=> I am a bit confused now. Altough I get a result in JSON format using AJAX, I want to publish it in this View 'About'. The View already have #model defined, so as soon as I get the result, I want the view to load it automatically as I don't think its a good option to create html controls in Javascript.
=> Is it possible or do I have to fill control one by one.
=> I am new in to MVC, so could you let me know any good suggestion.
Controller:
public ActionResult About()
{
var model = repo.GetModel();
return PartialViewResult("about", model);
}
jQuery:
$.ajax("/Controller/About/", {
type: "GET",
success: function (view) {
$("#aboutDiv").html(view);
}
});
In Main View:
<div id="aboutDiv"><div>
You need to give your elements some id or class that will allow you to interact with them easily on the client. Then, when you get your response, take the values from the JSON data and update the elements (using the id/class to find it) with the new value. I'm assuming you don't have any special template defined for your strings, adjust the selectors in the code as necessary to account for it if you do.
View
<p class="testDisplay"> #Html.DisplayFor(m=>m.test) </p>
<p class="test1Display"> #Html.DisplayFor(m=>m.test1) </p>
Client code
$(document).ready(function () {
var itemName = "#btn-about";
$(itemName).click(function () {
$.ajax({
type: 'GET',
dataType: 'Json',
url: '/Home/About',
success: function (data) {
$('.testDisplay').html(data.test);
$('.test1Display').html(data.test1);
},
error: function (xhr, ajaxOption, thorwnError) {
console.log("Error")
},
processData: false,
async: true
});
});
});
Instead of returning the data you will have to return the view as string and the use jquery to replace the result.
Controller:
public JsonResult About()
{
var model = // Your Model
return Json((RenderRazorViewToString("ViewNameYouWantToReturn", model)), JsonRequestBehavior.AllowGet);
}
[NonAction]
public string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
Then using jquery you can replace the result in container for eg: div as follows:
$.ajax({
type: 'GET',
dataType: 'Json',
url: '/Home/About',
success: function (result) {
$("#divId").replaceWith(result);
},

Returning List as Json and viewbag from same controller action

I am working on asp.net MVC 3 applciation. I have a jquery ui dialog. On Ok button of this dialog, I am opening another jquery ui dialogue. In order to populate the newly opened popup, I am using jquery ajax call which returns a collection. I am using this collection to create table rows. Code is here:
$("#Prices").dialog({
autoOpen: false,
autoResize: true, buttons: {
"OK": function () {
var PirceCurrencies = $('#PirceCurrencies').val();
jQuery("#hdCurrencyId").val(PirceCurrencies);
jQuery(this).dialog('close');
$.ajax({
type: "POST",
dataType: "json",
url: "/Home/GetRecordingRates",
data: { Id: $("#hdCurrencyId").val() },
success: function (data) {
$("#results").find("tr:gt(0)").remove();
var messages = data.Result;
$.each(messages, function(k, v) {
var row = $('<tr>');
row.append($('<td>').html(v.DialPrefix));
row.append($('<td>').html(v.Rate));
$('#results').append(row);
});
jQuery('#RecordingRates').dialog({ closeOnEscape: false });
$(".ui-dialog-titlebar").hide();
$("#RecordingRates").dialog({ dialogClass: 'transparent' });
$('#RecordingRates').dialog('open');
}
});
}
},
open: function () {
$('.ui-dialog-buttonset').find('button:contains("OK")').focus();
$('.ui-dialog-buttonset').find('button:contains("OK")').addClass('customokbutton');
}
});
and controller action is:
public JsonResult GetRecordingRates(int Id)
{
List<DefaultRateChart> defaultRateCharts = new List<DefaultRateChart>();
Currency currency = new Currency();
using (IDefaultRateChartManager defaultRateChartManager = new ManagerFactory().GetDefaultRateChartManager())
{
defaultRateCharts = defaultRateChartManager.GetAll().Where(rc => rc.Currency.Id == Id
&& (!rc.NumberPrefix.StartsWith("#") && !rc.NumberPrefix.Equals("Subscription")
&& !rc.NumberPrefix.Equals("Default")) && rc.AccountCredit == "Credit").ToList();
}
using (ICurrencyManager currencyManager = new ManagerFactory().GetCurrencyManager())
{
currency = currencyManager.GetById(Id);
ViewBag.currecycode = currency.CurrencyCode;
ViewBag.countrycode = currency.CountryCode;
}
return this.Json( new {
Result = ( from obj
in defaultRateCharts
select new {
Id = obj.Id,
DialPrefix = obj.NumberPrefix,
Rate = obj.PurchaseRates
}
)
}, JsonRequestBehavior.AllowGet);
}
All this works fine but I need to show some other data on newly opened popup other than the collection which populates/create html table rows. Fort that do I need to make another ajax call to another controller action which will return the data ?
Please suggest
Look at what you return now in your controller:
new {
Result = ( ... )
}
You are returning an object with 1 property named Result. In your javascript code you get that object returned named data and you retrieve the Result property as your list.
What stops you from adding more properties to that list?
new {
result = ( ... ),
currencyCode = currency.CurrencyCode,
countryCode = currency.CountryCode
}
In javascript you can then use data.currencyCode and data.countryCode
From Controller Action Method you can Return Dictionary like below.
Sample Code - C#
var dic = new List<KeyValuePair<short, object>>
{
new KeyValuePair<Int16, object>(1, SomeObj),
new KeyValuePair<Int16, object>(2, SomeObj),
new KeyValuePair<short, object>(3, SomeObj),
new KeyValuePair<Int16, object>(4, SomeObj)
};
return Json(dic, JsonRequestBehavior.AllowGet);
Sample Code - JQuery- Access Dictionary objects
var obj1; //Global Variables
var obj2; //Global Variables
var obj3; //Global Variables
var obj4; //Global Variables
$.ajax({
url: url,
async: true,
type: 'GET',
data: JSON.stringify({ Parameter: Value }),
beforeSend: function (xhr, opts) {
},
contentType: 'application/json; charset=utf-8',
complete: function () { },
success: function (data) {
DataSources(data);
}
});
function DataSources(dataSet) {
obj1 = dataSet[0].Value; //Access Object 1
obj2 = dataSet[1].Value; //Access Object 2
obj3 = dataSet[2].Value; //Access Object 3
obj4 = dataSet[3].Value; //Access Object 4
}
return a Dictionary from your controller.
convert your collection to string and other object to string and return
dictionary<int, string>
in your javascript sucess function,
JSON.parse(data[0].key) will give you your collection
This will give you an idea
bool inCart = false;
Cart MyCart = default(Cart);
Dictionary<string, string> Result = new Dictionary<string, string>();
Result.Add("inCart", inCart.ToString().ToLower());
Result.Add("cartText", MyCart.CartText());
string ResultString = new JavaScriptSerializer().Serialize(Result);
return ResultString;
Here I am adding two types to a dictionary and returning my serialized dictionary

Send list/array as parameter with jQuery getJson

I have the following where I'm trying to send list/array to MVC controller method:
var id = [];
var inStock = [];
$table.find('tbody>tr').each(function() {
id.push($(this).find('.id').text());
inStock.push($(this).find('.stocked').attr('checked'));
});
var params = {};
params.ids = id;
params.stocked = inStock;
$.getJSON('MyApp/UpdateStockList', params, function() {
alert('finished');
});
in my contoller:
public JsonResult UpdateStockList(int[] ids, bool[] stocked) { }
both paramaters are null.
Note that if I change the params to single items
params.ids = 1;
params.stocked = true;
public JsonResult UpdateStockList(int ids, bool stocked) { }
then it works ok, so I don't think it's a routing issue.
Try setting the traditional flag:
$.ajax({
url: '/home/UpdateStockList',
data: { ids: [1, 2, 3], stocked: [true, false] },
traditional: true,
success: function(result) {
alert(result.status);
}
});
works fine with:
public ActionResult UpdateStockList(int[] ids, bool[] stocked)
{
return Json(new { status = "OK" }, JsonRequestBehavior.AllowGet);
}
Besides calling .ajax() instead of .getJSON() as Darin suggests or setting the global jQuery.ajaxSettings.traditional to true as jrduncans suggests, you can also pass the result of calling the jQuery .param() function on your params object:
var id = [];
var inStock = [];
$table.find('tbody>tr').each(function() {
id.push($(this).find('.id').text());
inStock.push($(this).find('.stocked').attr('checked'));
});
var params = {};
params.ids = id;
params.stocked = inStock;
$.getJSON('MyApp/UpdateStockList', $.param(params, true), function() {
alert('finished');
});
Unfortunately, while it seems that jquery provides a "traditional" flag to toggle this behavior on jQuery.ajax, it does not on jQuery.getJSON. One way to get around this would to be set the flag globally:
jQuery.ajaxSettings.traditional = true;
See the documentation for jQuery.param: http://api.jquery.com/jQuery.param/
Also see the release notes for this change: http://jquery14.com/day-01/jquery-14 (search for 'traditional')
In the view, generate multiple named fields (not id, as id should be unique per field), noting the use of Name not name:
#foreach (var item in Model.SomeDictionary)
{
#Html.TextBoxFor(modelItem => item.Value.SomeString, new { Name = "someString[]" })
}
Then retrieve the input field values using jQuery, so:
var myArrayValues = $('input[name="someString[]"]').map(function () { return $(this).val(); }).get();
You can use this directly in jQuery / AJAX as follows:
$.ajax({
type: "POST",
url: "/MyController/MyAction",
dataType: 'json',
data: {
someStrings: $('input[name="someString[]"]').map(function () { return $(this).val(); }).get(),
someDates: $('input[name="someDate[]"]').map(function () { return $(this).val(); }).get(),
Then in the controller action in MVC:
[HttpPost]
public JsonResult MyAction(string[] someStrings, DateTime[] someDates...

Resources