List<IFormFile> files gets nothing from dropzone post mvc - asp.net-mvc

I'm trying to send images from dropzone to my controller mvc project by httpPost
The forms are calling correctly the IActionResult but the files count are always 0
When the forms load I get
but I'm already giving a URL. Don't know what's the error.
Here is my cshtml script of dropzone config
#section Scripts
{
<link rel="stylesheet" href="~/css/basic.css" />
<link rel="stylesheet" href="~/css/dropzone.css" />
<script type="text/javascript" src="~/js/dropzone.js"></script>
<script type="text/javascript" src="~/js/dropzone-amd-module.js"></script>
<script>
Dropzone.autoDiscover = false;
$(document).ready(function () {
$('#myDropzone').dropzone({
url:"/Aprovacoes/SaveUploadedFile",
method: "post",
//parameter name value
paramName: function () { "files" },
//clickable div id
clickable: '#previews',
//preview files container Id
previewsContainer: "#previews",
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
// url:"/", // url here to save file
maxFilesize: 100,//max file size in MB,
addRemoveLinks: true,
dictResponseError: 'Server not Configured',
acceptedFiles: ".png,.jpg,.gif,.bmp,.jpeg,.pdf",// use this to restrict file type
init: function () {
var self = this;
// config
self.options.addRemoveLinks = true;
self.options.dictRemoveFile = "Delete";
//New file added
self.on("addedfile", function (file) {
console.log('new file added ', file);
$('.dz-success-mark').hide();
$('.dz-error-mark').hide();
});
// Send file starts
self.on("sending", function (file) {
console.log('upload started', file);
$('.meter').show();
});
// File upload Progress
self.on("totaluploadprogress", function (progress) {
console.log("progress ", progress);
$('.roller').width(progress + '%');
});
self.on("queuecomplete", function (progress) {
$('.meter').delay(999).slideUp(999);
});
// On removing file
self.on("removedfile", function (file) {
console.log(file);
});
$('#Submit').on("click", function (e) {
e.preventDefault();
e.stopPropagation();
// Validate form here if needed
if (self.getQueuedFiles().length > 0) {
self.processQueue();
} else {
self.uploadFiles([]);
$('#myDropzone').submit();
}
});
self.on("successmultiple", function (files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
});
}
});
})
</script>
And here is the form
#using (Html.BeginForm("SaveUploadedFile", "Aprovacoes", FormMethod.Post, new { #name = "myDropzone", id = "myDropzone", #enctype = "multipart/form-data" }))
{
<br />
<div>
<div id="previews" class="dz-default dz-message box__input dropzone">
<div style="text-align:center">
<i class="fa fa-cloud-upload" style="font-size:23px;position:relative;top:4px;"></i> <span style="margin-left:20px">Drop files to attach or browse</span>
</div>
</div>
</div>
<br />
<div>
<input type="submit" id="Submit" name="Submit" class="btn btn-success m-t-5" value="Submit" />
</div>
}
My controller httpPost method
[HttpPost]
public IActionResult SaveUploadedFile(List<IFormFile> files)
{
//do stuff
}
always come 0

This is my working solution:
View Part
#using (Ajax.BeginForm("YourAction", "YourController", FormMethod.Post, new AjaxOptions { HttpMethod = "POST", OnBegin = "OnBegin", OnSuccess = "OnSuccess", OnFailure = "OnFailure" }, new { #id = "ajaxForm", #enctype = "multipart/form-data" }))
{
<div class="card">
<div class="card-body">
#Html.AntiForgeryToken()
<div class="col-md-12 dropzone">
<div class="dropzone-previews" id="dropzonePreview">
<i class="icon-file-upload icon-5x absolute-center text-muted"></i>
</div>
</div>
</div>
<div class="row form-group mt-3">
<div class="col-md-12">
<input class="btn btn-inverse btn-primary" id="btnSubmit" name="inputSubmit" type="submit" value="Save" />
</div>
</div>
</div>
</div>
}
Script Part
Dropzone.autoDiscover = false;
var options = {
paramName: "PhotoFiles",
addRemoveLinks: true,
autoDiscover: false,
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 5,
thumbnailWidth: 250,
thumbnailHeight: 250,
dictRemoveFile: 'Delete',
previewsContainer: '#dropzonePreview',
clickable: '.dropzone',
acceptedFiles: ".jpeg,.jpg,.png",
};
var dropZone = new Dropzone("form#ajaxForm", options);
dropZone.element.querySelector("input[type=submit]").addEventListener("click", function (e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
// if dropzone has file process them, if not send empty array
if (dropZone.getQueuedFiles().length > 0) {
dropZone.processQueue();
} else {
$("#ajaxForm").submit();
}
});
dropZone.on("successmultiple", function (files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
OnSuccess(response);
});
dropZone.on("errormultiple", function (files, response) {
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
OnFailure(response);
});
Controller Part
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult InsertPhotos()
{
if (Request.Files.Count > 0)
{
for (int i = 0; i < Request.Files.Count; i++)
{
//process files
}
}
//return some result
return Json(result, JsonRequestBehavior.AllowGet);
}
Hope it helps.

Related

How do I handle multiple files in a form without knowing the amount of them?

I'm creating a website for a printing store, and when adding a product to the cart, it can't just add it to the cart, it needs some information from the user (for example, a pdf or an image).
This information varies from one product to the other, and is defined in Product.InfoNeeded which is a list of Infos (a class) which has a the exact type of information this product needs.
Some products need just one file, some need 2, and some need 3, so I created such a form:
#model xyz.ViewModels.CartItemFormViewModel
#{
ViewBag.Title = "xyz";
}
#using (Html.BeginForm("Save", "CartItems"))
{
#Html.ValidationSummary(true, "Please fix the following errors:")
var index = 0;
foreach (var info in Model.InfoNeeded)
{
index++;
<div class="form-group">
#Html.Label(info.Label)
<input type="file" id="#index" name="file_#index" class="form-control-file">
</div>
}
<div class="form-group">
#Html.AntiForgeryToken()
<button type="submit" class="btn btn-primary" id="submitButton">Submit</button>
</div>
}
This is the ViewModel:
public class CartItemFormViewModel
{
public CartItem CartItem { get; set; }
public List<Info> InfoNeeded { get; set; }
public CartItemFormViewModel(int productId, List<Info> infoNeeded)
{
CartItem = new CartItem(productId);
InfoNeeded = infoNeeded;
}
}
This is the Add Action:
public ActionResult Add(int id)
{
var infoNeeded = _context.Products
.Include(p => p.InfoNeeded)
.Single(p => p.Id == id)
.InfoNeeded;
var viewModel = new CartItemFormViewModel(id, infoNeeded);
return View("CartItemForm", viewModel);
}
Now, how do I get these files here by the Save action?
public ActionResult Save()
{
return Content("");
}
You should update your model to include something like this
public IEnumerable<HttpPostedFileBase> CartFiles { set; get; }
This way you can intercept all submitted files in for and process them. This is of course one part. Problem begins when you are trying multiupload in form. I have tried many plugins so far and dropzone was the only one that was able to process multiple files in submit form without problems like deleting and re adding files.
In case you choose dropzone this is optimal configuration when using form submit.
Dropzone.autoDiscover = false;
var options = {
paramName: "CartFiles",
addRemoveLinks: true,
autoDiscover: false,
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 5,
thumbnailWidth: 250,
thumbnailHeight: 250,
dictRemoveFile: "#Resources.Strings.Delete",
previewsContainer: '#dropzonePreview',
maxFiles: 5 ), <-- remove this if unlimited
clickable: '.dropzone',
acceptedFiles: ".jpeg,.jpg,.png,.pdf",
};
var dropZone = new Dropzone("form#productForm", options);
Edit:
You can read about dropzone here DropzoneJS is an open source library that provides drag’n’drop file uploads with image previews.
I am not able to completely review your code, based on snippets you provided, but basically there is no need to loop and crate input files manually.
Example pseudocode
View - I am using ajax to update controller and return feedback to user and view. Of course its up to you.
#using (Ajax.BeginForm("Save", "CartItems", FormMethod.Post, new AjaxOptions { HttpMethod = "POST", OnBegin = "OnBegin", OnSuccess = "OnSuccess", OnFailure = "OnFailure" }, new { #id = "ajaxForm", #class = "was-validated", #enctype = "multipart/form-data" }))
{
<div class="card">
<div class="card-body">
#Html.AntiForgeryToken()
<div class="row">
<label>Please drop your files here</label>
<div class="col-md-12 dropzone">
<div class="dropzone-previews" id="dropzonePreview">
<i class="icon-file-upload icon-5x absolute-center text-muted"></i>
</div>
</div>
</div>
<div class="row form-group mt-3">
<div class="col-md-12">
<input class="btn btn-inverse btn-primary" id="btnSubmit" name="inputSubmit" type="submit" value="#Resources.Strings.Save" title='#Resources.Strings.Save' />
<input class="btn btn-green cancel" id="btnCancel" name="inputCancel" type="button" value="#Resources.Strings.Cancel" title='#Resources.Strings.Cancel' />
</div>
</div>
</div>
</div>
}
<script src="~/../dropzone.min.js"></script>
<script>
$(document).ready(function () {
Dropzone.autoDiscover = false;
var options = {
paramName: "CartFiles",
addRemoveLinks: true,
autoDiscover: false,
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 5,
thumbnailWidth: 250,
thumbnailHeight: 250,
dictRemoveFile: "#Resources.Strings.Delete",
previewsContainer: '#dropzonePreview',
clickable: '.dropzone',
acceptedFiles: ".jpeg,.jpg,.png",
};
var dropZone = new Dropzone("form#ajaxForm", options);
dropZone.element.querySelector("input[type=submit]").addEventListener("click", function (e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
// if dropzone has file process them, if not send empty array
if (dropZone.getQueuedFiles().length > 0) {
dropZone.processQueue();
} else {
$("#ajaxForm").submit();
}
});
});
Controller part
public JsonResult Save()
{
if (Request.Files.Count > 0)
{
for (int i = 0; i < Request.Files.Count; i++)
{
[YourModel].CartFiles.Append(Request.Files[i]);
}
// do whatever is needed to save files
}
}

MVC POP Up and PostBack

I have a MVC c#, signalR project where Agent follow below steps in Application
Login To application. Once login success application hides Login div panel & displays list of campaign & telephony buttons
Application displays list of campaigns agent is assigned to
Application displays button in front of each campaign to set Ready / Not Ready in campaign. In this case it is RestAPI & Telemarketing
If agent need to set himself not ready in campaign it opens popup window with list not ready reasons.
Issue is :
When Agent select reason and submit it application post back it lost view and reset to login window.
Controller action after submit of breakreason in PopUp window:
public ActionResult SetBreak(breakReasonModel form)
{
string tok=form.accessToken;
string cmp = form.campaign;
string selreason = "";
for (int i=0;i < form.arrReasons.Length;i++)
{
selreason = form.arrReasons[i];
}
SetBreak obj = new SetBreak();
System.Collections.Generic.List<ISCampaigns> IScampaignNames = new System.Collections.Generic.List<ISCampaigns>();
IScampaignNames = obj.setNotReadyInCampaign(tok, cmp, selreason);
return RedirectToAction("Index");
}
PopUp Partial View :
#using Altitude.IntegrationServer.RestApiWebApp.Models
#model Altitude.IntegrationServer.RestApiWebApp.Models.breakReasonModel
<div id="divBreakReasons">
#using (Html.BeginForm("SetBreak", "Home"))
{
#Html.ListBoxFor(m => m.arrReasons, Model.reasonsMultiSelectList, new { #class = "form-control" })
#Html.TextBoxFor(model => model.accessToken, new { id = "txtaccessToken" })
#Html.TextBoxFor(model => model.campaign, new { id = "txtcampaign" })
<br />
<button id="btn" type="submit" class="btn btn-block bg-primary" value="Submit" >Submit</button>
<br />
}
</div>
Index.chtml
<div class="row">
<div class="col-md-4 table-responsive" id="telButtons">
<table id="tblTelephony" class="table">
--Telephony Buttons
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="col-md-4 table-responsive">
<p id="demo"></p> // Campaign table with Ready/Not Ready buttons
</div>
</div>
//ajax call to open popup
<div id="dialog" style="display: none"></div>
<script type="text/javascript">
function getBreak(nrReason) {
$("#dialog").dialog({
autoOpen: false,
modal: true,
});
$.ajax({
type: "POST",
url: "#Url.Action("popupBreak","Home")",
data: '{breakReason : "' + dataToSend + '",accessToken : "' +acc+ '",campaign : "' + cmp + '"}',
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (response) {
$('#dialog').html(response);
$('#dialog').dialog('open');
console.log(response);
},
failure: function (response) {
},
error: function (response) {
}
});
}
</script>
It does exactly what you coded. If you need to return result to current view you should use ajax call that will return action result.
example
#using (Ajax.BeginForm("Action", "Controller", FormMethod.Post, new AjaxOptions() { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "YourTargetForResult" }, new { #id = "ajaxForm" }))
You must reference jquery.unobtrusive-ajax.js to receive postback in current view.
Example based on your comment:
<input type="hidden" id="hdnResponseMessage" /> // add dom object where response hits
#using (Ajax.BeginForm("SetBreak", "YourControllerName", FormMethod.Post, new AjaxOptions() { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "hdnResponseMessage" }, new { #id = "form" }))
{
#Html.ListBoxFor(m => m.arrReasons, Model.reasonsMultiSelectList, new { #class = "form-control" })
#Html.TextBoxFor(model => model.accessToken, new { id = "txtaccessToken" })
#Html.TextBoxFor(model => model.campaign, new { id = "txtcampaign" })
<br />
<button id="btn" type="submit" class="btn btn-block bg-primary" value="Submit" >Submit</button>
<br />
}
Conroller:
[HttpPost]
public JsonResult SetBreak(breakReasonModel form)
{
string tok=form.accessToken;
string cmp = form.campaign;
string selreason = "";
for (int i=0;i < form.arrReasons.Length;i++)
{
selreason = form.arrReasons[i];
}
SetBreak obj = new SetBreak();
System.Collections.Generic.List<ISCampaigns> IScampaignNames = new System.Collections.Generic.List<ISCampaigns>();
IScampaignNames = obj.setNotReadyInCampaign(tok, cmp, selreason);
return Json("SetBreak");
}
jQuery set listener in document ready:
// add dom object listener
$('#hdnResponseMessage').bind('DOMNodeInserted', function () {
var txt = $('#hdnResponseMessage').text();
if (txt == 'SetBreak')
{
//do your stuff here;
}
});

asp.net mvc Ajax submit form with fileinput in jquery plugin

I'm having problems with an form.
I need to submit a form with ajax with fileinput in the form. In this form, I use the plugin with fileinput. This is the website
Here is my code:
<link href="~/Content/Plugin/bootstrap-fileinput-master/css/fileinput.min.css" rel="stylesheet" />
<script src="~/Content/Plugin/bootstrap-fileinput-master/js/fileinput.min.js"></script>
<script src="~/Content/Plugin/bootstrap-fileinput-master/js/fileinput_locale_zh.js"></script>
#using (Ajax.BeginForm(null, null, new AjaxOptions(){
HttpMethod = "post",Url = Url.Action("Upload", "WorkItem"),
InsertionMode = InsertionMode.Replace, LoadingElementDuration = 2000,
OnSuccess = "completed" },
new { role = "form", enctype = "multipart/form-data" }))
{
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">TITLE</span>
<input type="text" name="Descr" class="form-control" aria-describedby="basic-addon1">
</div>
<div class="m-b-5"></div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">POINT</span>
<input type="text" name="Point" class="form-control" aria-describedby="basic-addon1">
</div>
<div class="m-b-5"></div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">DESCR</span>
<input type="text" name="Descr" class="form-control" aria-describedby="basic-addon1">
</div>
<div class="m-b-5"></div>
<input id="file-0a" name="file" class="file" type="file" data-min-file-count="1">
<br />
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
}
When I click the submit button, no file can be accepted. What is going wrong?
As #Stepher Muecke told #Ajax.BeginForm can not be used to post Files.
I dont have a idea about plugin.I use the following method:
$("#btnUploadExcel").click(function () {
if ($("#newuploadexcel").val() == '') {
notie.alert(2, "Please Select Any File", 2);
}
else {
if (window.FormData!= undefined) {
var fileUpload = $("#newuploadexcel").get(0);
var files = fileUpload.files;
// Create FormData object
var fileData = new FormData();
// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
// Adding one more key to FormData object
// fileData.append('contentId', contentId); commented as now supplierId is passed in the excel itself
$.ajax({
url: '/BulkStock/UploadExcel',
data: fileData,
type: "POST",
async: true,
dataType: 'json',
contentType: false,
processData: false,
success: function (result) {
var data = result.message;
//1=Failure, No excel
//2= Failue, with excel
//3=success, no excel
if (result.errmsg == '3') {
notie.alert(1, data, 6);
}
else if (result.errmsg == '1') {
notie.alert(3, data, 6);
}
else {
window.location = result.link;
notie.alert(3, data, 10);
}
},
error: function (response) {
console.log(response.responseText);
},
failure: function (response) {
console.log(response.responseText);
}
});
$("#newUpload").modal('hide');
} else {
notie.alert(3, "FormData is not supported.", 3);
}
}
});
And my controller to get file is:
public JsonResult UploadExcel()
{
string filePath = String.Empty;
string fileName = string.Empty;
if (Request.Files.Count > 0)
{
// Get all files from Request object
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFileBase file = files[i];
fileName = file.FileName;
string extension = System.IO.Path.GetExtension(fileName);
if (extension.Equals(".xls") || extension.Equals(".xlsx"))
{
var now = DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture);
string my3DigitRandomNumber = now.Substring(now.Length - 7, 3);
fileName = (file.FileName.Replace(extension, "")) + (my3DigitRandomNumber + extension);
filePath = string.Format("{0}/{1}", Server.MapPath("~/excelfiles"), fileName);
file.SaveAs(filePath);
}
}
}
}
Create a folder with the name "excelfiles" in your solution

How to pass selected files in Kendo Upload as parameter in ajax request

After much of struggle im posing this question. Im using a Kendo Upload on a page. Am able to post the selected files on the asyn mode with whe the page has Html.BeginForm. But I'm not able to send file details as HttpPostedFileBase when I use ajax request to send data to the controller.
Following is my html
<form class="form-horizontal" role="form">
<div class="form-group">
#Html.Label("Complaint Name", new { #class = "col-sm-3 control-label" })
<div class="col-sm-4">
#Html.TextBoxFor(
m => m.ComplaintName,
new
{
#TabIndex = "1",
#class = "form-control input-sm",
disabled = true
})
</div>
</div>
<div class="form-group">
#Html.Label("Complaint Details", new { #class = "col-sm-3 control-label" })
<div class="col-sm-4">
#Html.TextBoxFor(
m => m.ComplaintDetails,
new
{
#TabIndex = "2",
#class = "form-control input-sm",
disabled = true
})
</div>
</div>
<div class="form-group">
#Html.Label("Choose files to upload", new { #class = "col-sm-3 control-label" })
<div class="col-sm-9 nopaddingforTextArea">
<input name="files" id="files" type="file" />
</div>
</div>
<div class="form-group">
<div>
<input id="btnSubmit" class="btn btn-primary pull-right" type="button" />
</div>
</div>
</form>
Following is my action
public ActionResult SaveComplaintDetails(string complaintName, string complaintDetails, IEnumerable<HttpPostedFileBase> files)
{
}
Following is my js
$("#files").kendoUpload({
async: {
saveUrl: '#Url.Action("EsuperfundCommentsBind", ClientInboxConstants.NewQuery)',
autoUpload: false
},
multiple: true
});
$("#btnSubmit").click(function () {
//Ajax call from the server side
$.ajax({
//The Url action is for the Method FilterTable and the Controller PensionApplicationList
url: '#Url.Action("SaveComplaintDetails", "Complaints")',
//The text from the drop down and the corresponding flag are passed.
//Flag represents the Index of the value in the dropdown
data: {
complaintName: document.getElementById("ComplaintName").value,
complaintDetails: document.getElementById("ComplaintDetails").value,
files: //What to pass here??
},
contentType: "application/json; charset=utf-8",
//Json data
datatype: 'json',
//Specify if the method is GET or POST
type: 'GET',
//Error function gets called if there is an error in the ajax request
error: function () {
},
//Gets called on success of the Ajax Call
success: function (data) {
}
});
});
My question is how to pass the selected files in Kendo Upload in ajax as a parameter?
Any help in this aspect would be really appreciated.
If your view is based on a model and you have generated the controls inside <form> tags, then you can serialize the model to FormData using:
<script>
var formdata = new FormData($('form').get(0));
</script>
This will also include any files generated with: <input type="file" name="myImage" .../> and post it back using:
<script>
$.ajax({
url: '#Url.Action("YourActionName", "YourControllerName")',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
});
</script>
and in your controller:
[HttpPost]
public ActionResult YourActionName(YourModelType model)
{
}
or (if your model does not include a property for HttpPostedFileBase)
[HttpPost]
public ActionResult YourActionName(YourModelType model,
HttpPostedFileBase myImage)
{
}
If you want to add additional information that is not in the form, then you can append it using
<script>
formdata.append('someProperty', 'SomeValue');
</script>
**Example Usage :**
View :
#using (Html.BeginForm("Create", "Issue", FormMethod.Post,
new { id = "frmCreate", enctype = "multipart/form-data" }))
{
#Html.LabelFor(m => m.FileAttachments, new { #class = "editor-label" })
#(Html.Kendo().Upload()
.HtmlAttributes(new { #class = "editor-field" })
.Name("files")
)
}
<script>
$(function () {
$('form').submit(function (event) {
event.preventDefault();
var formdata = new FormData($('#frmCreate').get(0));
$.ajax({
type: "POST",
url: '#Url.Action("Create", "Issue")',
data: formdata,
dataType: "json",
processData: false,
contentType: false,
success: function (response) {
//code omitted for brevity
}
});
});
});
</script>
*Controller :*
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = null)] Model viewModel, IEnumerable<HttpPostedFileBase> files)
{
//code omitted for brevity
return Json(new { success = false, message = "Max. file size 10MB" }, JsonRequestBehavior.AllowGet);
}
<script>
$(function () {
$('form').submit(function (event) {
event.preventDefault();
var formdata = new FormData($('#createDetail').get(0));
$.ajax(
{
type: 'POST',
url: '#Url.Action("Detail_Create", "Product")',
data: formdata,
processData: false,
success: function (result) {
if (result.success == false) {
$("#divErr").html(result.responseText);
} else {
parent.$('#CreateWindowDetail').data('kendoWindow').close();
}
},
error: function (xhr, ajaxOptions, thrownError) {
$("#divErr").html(xhr.responseText);
}
});
});
});
#using (Html.BeginForm("Detail_Create", "Product", FormMethod.Post, new { id = "createDetail", enctype="multipart/form-data"}))
{
<div id="divErr" class="validation-summary-errors"></div>
<fieldset>
<ol>
<li>
#Html.LabelFor(m => m.Price)
#(Html.Kendo().NumericTextBoxFor(m => m.Price).Name("Price").Format("{0:0}")
.HtmlAttributes(new { style = "width:100%" })
)
</li>
<li>
#Html.LabelFor(m => m.Description)
#Html.TextBoxFor(model => model.Description, new { #class = "k-textbox", id = "Description", style = "width:100%;" })
</li>
<li>
#Html.LabelFor(m => m.Group)
#(Html.Kendo().ComboBox()
.Name("Group")
.Placeholder("Введите группу детали")
.DataTextField("Name")
.DataValueField("Id")
.HtmlAttributes(new { style = "width:100%;" })
.Filter("contains")
.MinLength(1)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Group_Read_ComboBox", "Product");
})
.ServerFiltering(true);
})
)
</li>
<li>
#Html.LabelFor(m => m.Image)
#(Html.Kendo().Upload()
.Name("files")
)
</li>
</ol>
</fieldset>
<button type="submit" id="get" class="k-button">Добавить</button>
}
[HttpPost]
public ActionResult Detail_Create(DetailModel model, IEnumerable<HttpPostedFileBase> files)
{
string error = string.Empty;
if (ModelState.IsValid)
{
.....
}
IEnumerable<System.Web.Mvc.ModelError> modelerrors = ModelState.SelectMany(r => r.Value.Errors);
foreach (var modelerror in modelerrors)
{
error += "• " + modelerror.ErrorMessage + "<br>";
}
return Json(new { success = false, responseText = error }, JsonRequestBehavior.AllowGet);
}
after pressing the button, the controller null comes to how to fix. 2 days already sitting, and the time comes to an end

ajax form submit using jquery dialog

I want to show a confirmation dialog and if user press 'continue', the form will be submit.
This is the jquery code:
$(document).ready(function () {
$('#submit').click(function () {
$('#confirmation-dialog').dialog('open');
return false; // prevents the default behaviour
});
$('#confirmation-dialog').dialog({
autoOpen: false, width: 400, resizable: false, modal: true, //Dialog options
buttons: {
"Continue": function () {
$(this).dialog('close');
var form = $('transferForm', this);
$(form).submit();
return true;
},
"Cancel": function () {
$(this).dialog("close");
return false;
}
}
});
});
And this is the form:
#using (Ajax.BeginForm("Transfer", "Location", null, new AjaxOptions
{
UpdateTargetId = "update-message",
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
//OnBegin = "ajaxValidate",
OnSuccess = "updateSuccess"
}, new { #id = "transferForm" }))
{
<div style="width:600px;">
<div class="editorLabel">
#Html.LabelFor(m => m.FromEmail)
</div>
<div class="editorText">
#Html.TextBoxFor(m => m.FromEmail)
</div>
<div class="clear"></div>
<div class="editorLabel">
#Html.LabelFor(m => m.ToEmail)
</div>
<div class="editorText">
#Html.TextBoxFor(m => m.ToEmail)
</div>
<div class="clear"></div>
<p>
<input type="submit" name="submit" value="Transfer" class="btn" id="submit"/>
</p>
</div>
}
<div id="update-message"></div>
<div id="commonMessage"></div>
<div id="confirmation-dialog">
<p>Are you sure you want to proceed with transfer ?
</p>
</div>
But after the confirmation, the form is not submitted.
What could be wrong here?? any ideas??
Try changing this:
var form = $('transferForm', this);
$(form).submit();
to:
$("#IDofForm").submit();
as this inside the dialogs event handlers probably does'nt refer to what you think it does, and you probably don't have an element with a transferForm tagname (which is what you're targeting when not using # or . in front of the selector) ?

Resources