ajax form submit using jquery dialog - asp.net-mvc

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) ?

Related

List<IFormFile> files gets nothing from dropzone post 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.

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;
}
});

How to load jqgrid on button click and send parameters to the action in jqGrid 4.6.0 in MVC

I want to load every year's data in jqgrid when I click on a button and after loading a modal form and selecting the year from drop down list. a diagram of the steps
but i don't know how to do this.
And this is my source code :
<!-- Page content -->
<div class="w3-content" style="max-width: 100%">
<div class="container" style="width:40%;margin-top:2%">
Filter
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
×
</div>
<div class="modal-body">
<form id="myForm" dir="rtl">
<div class="form-group">
<label>Year</label>
#Html.DropDownListFor(model => model.YEAR_ABBR, ViewBag.YearList as MultiSelectList, "--select--", new { #class = "form-control", #id = "ddlYear", multiple = "multiple" })
</div>
</form>
</div>
<div class="modal-footer">
Cancel
<input type="reset" value="GetRep" class="btn btn-success" id="btnSubmit" />
</div> </div>
</div> </div> </div>
<div dir="rtl" align="center" style="overflow:auto" class="tablecontainer">
<div id="rsperror"></div>
<table id="list" cellpadding="0" cellspacing="0"></table>
<div id="pager" style="text-align:center;"></div>
</div>
Now my script is something like this:
<script type="text/javascript">
$(document).ready(function () {
bindData();
$("#btnSubmit").click(function () {
$('#list').trigger('reloadGrid'); })
});
var bindData = function () {
$('#list').jqGrid({
url: '#Url.Action("Get_RepContracts","Home")',
postData: { YEAR_ABBR: function () { return $('#YEAR_ABBR').val(); } },
datatype: 'json',
jsonReader: {
root: "Rows",
page: "Page",
},
mtype: 'GET',
//columns names
colNames: ['Vahed_Descript' ],
colModel: [
{ name: 'Vahed_Descript', index: 'Vahed_Descript', align: 'right', width: 200, sorttype: "number", }
],
pager: $('#pager'),
rowNum: 800,
rowList: [ 800 ,1000],
sortname: 'Vahed_Descript',
hidegrid: false,
direction: "rtl",
gridview: true,
rownumbers: true,
footerrow: true,
userDataOnFooter: true,
loadComplete: function () {
calculateTotal();
$("tr.jqgrow:odd").css("background", "#E0E0E0");
},
loadError: function (xhr, st, err) {
jQuery("#rsperror").html("Type: " + st + "; Response: " + xhr.status + " " + xhr.statusText);
} , loadonce: true
}) ;
And here the button code ( My modal form works well. when I click the filter button, the filter options in my modal form appear, and then I select the year from year dropdownlist in modal and then i click the report button, after that the below code fires and I can see the selected year's data in action "Get_RepContracts" but it does not bind to my jqgrid):
Thanks in Advance...
UPDATE : Now My code is like below :
$(document).ready(function () {
bindData();
$("#btnSubmit").click(function () {
var myPostData = $('#list').jqGrid("getGridParam", "postData");
$('#list').trigger('reloadGrid');
$("#myModal").modal("hide");
}) });
var bindData = function () {
$('#list').jqGrid({
url: '#Url.Action("Get_RepContracts","Home")',
postData: {
YEAR_ABBR : function () { return $("#YEAR_ABBR").val();},
} ,
datatype: 'json',
jsonReader: { ........
It seems to me that you have small problem with the usage of correct id of select element. Your HTML code contains #id = "ddlYear" parameter of #Html.DropDownListFor:
#Html.DropDownListFor(
model => model.YEAR_ABBR,
ViewBag.YearList as MultiSelectList,
"--select--",
new {
#class = "form-control",
#id = "ddlYear",
multiple = "multiple"
}
)
but you still use
postData: {
YEAR_ABBR: function () { return $("#YEAR_ABBR").val(); }
}
To solve the problem you should just modify the code to
postData: {
YEAR_ABBR: function () { return $("#ddlYear").val(); }
}

How to create Multi-Level Treeview in ASP.NET MVC

I have implemented a code to create Tree View and also save it into database.
Controller
public ActionResult IndexMda()
{
using (BackendEntities context = new BackendEntities())
{
var plist = context.MDA.Where(p => p.PARENT_MDA_ID == null).Select(a => new
{
a.MDA_ID,
a.MDA_NAME,
a.MDA_DESCRIPTION,
a.ORGANIZATION_TYPE
}).ToList();
ViewBag.plist = plist;
}
GetHierarchy();
return View();
}
public JsonResult GetHierarchy()
{
List<MDA2> hdList;
List<MdaViewModel> records;
using (BackendEntities context = new BackendEntities())
{
hdList = context.MDA.ToList();
records = hdList.Where(l => l.PARENT_MDA_ID == null)
.Select(l => new MdaViewModel
{
MDA_ID = l.MDA_ID,
text = l.MDA_NAME,
MDA_DESCRIPTION = l.MDA_DESCRIPTION,
ORGANIZATION_TYPE = l.ORGANIZATION_TYPE,
PARENT_MDA_ID = l.PARENT_MDA_ID,
children = GetChildren(hdList, l.MDA_ID)
}).ToList();
}
return this.Json(records, JsonRequestBehavior.AllowGet);
// return View();
}
private List<MdaViewModel> GetChildren(List<MDA2> hdList, long PARENT_MDA_ID)
{
return hdList.Where(l => l.PARENT_MDA_ID == PARENT_MDA_ID)
.Select(l => new MdaViewModel
{
MDA_ID = l.MDA_ID,
text = l.MDA_NAME,
MDA_DESCRIPTION = l.MDA_DESCRIPTION,
ORGANIZATION_TYPE = l.ORGANIZATION_TYPE,
PARENT_MDA_ID = l.PARENT_MDA_ID,
children = GetChildren(hdList, l.MDA_ID)
}).ToList();
}
[HttpPost]
public JsonResult ChangeNodePosition(long MDA_ID, long PARENT_MDA_ID)
{
using (BackendEntities context = new BackendEntities())
{
var Hd = context.MDA.First(l => l.MDA_ID == MDA_ID);
Hd.PARENT_MDA_ID = PARENT_MDA_ID;
context.SaveChanges();
}
return this.Json(true, JsonRequestBehavior.AllowGet);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddNewNode(AddNode model)
{
try
{
if (ModelState.IsValid)
{
using (BackendEntities db = new BackendEntities())
{
MDA2 hierarchyDetail = new MDA2()
{
MDA_NAME = model.NodeName,
PARENT_MDA_ID = model.ParentName,
MDA_DESCRIPTION = model.NodeDescription,
ORGANIZATION_TYPE = model.NodeOrganizationType
};
db.MDA.Add(hierarchyDetail);
db.SaveChanges();
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
throw ex;
}
return Json(new { success = false }, JsonRequestBehavior.AllowGet);
}
The partial view is where the Tree View is created
Partial View
#model BPP.CCSP.Admin.Web.ViewModels.AddNode
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button"
class="close"
data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Add Node</h4>
</div>
<div class="modal-body">
#using (Html.BeginForm("AddNewNode", "Mda", FormMethod.Post, new { #id = "formaddNode", #class = "form-horizontal", role = "form", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="col-md-12">
<div class="col-md-6 row">
<div class="input-group">
<input type="text" class="form-control" value="Perent Node" readonly="readonly">
<span class="input-group-addon">
#Html.RadioButtonFor(model => model.NodeTypeRbtn, "Pn", new { #class = "btn btn-primary rbtnnodetype" })
</span>
</div>
</div>
<div class="col-md-6">
<div class="input-group ">
<input type="text" class="form-control" value="Child Node" readonly="readonly">
<span class="input-group-addon">
#Html.RadioButtonFor(model => model.NodeTypeRbtn, "Cn", new { #class = "rbtnnodetype" })
</span>
</div>
</div>
<br />
#Html.ValidationMessageFor(m => m.NodeTypeRbtn, "", new { #class = "alert-error" })
</div>
<div class="clearfix">
</div>
<div class="col-md-12">
<div class="petenddiv hidden">
#Html.Label("Select Parent")
#Html.DropDownList("ParentName", new SelectList(ViewBag.plist, "MDA_ID", "MDA_NAME"), "--select--", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.ParentName, "", new { #class = "alert-error" })
</div>
</div>
<div class="clearfix">
</div>
<div class="col-md-12">
<div>
#Html.Label("MDA Name")
#Html.TextBoxFor(model => model.NodeName, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.NodeName, "", new { #class = "alert-error" })
</div>
</div>
<div class="col-md-12">
<div>
#Html.Label("Description")
#Html.TextBoxFor(model => model.NodeDescription, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.NodeDescription, "", new { #class = "alert-error" })
</div>
</div>
<div class="col-md-12">
<div>
#Html.Label("Organization Type")
#Html.DropDownListFor(model => model.NodeOrganizationType, new List<SelectListItem>
{
new SelectListItem{Text = "Agency", Value = "Agency"},
new SelectListItem{Text = "Commission", Value = "Commission"},
new SelectListItem{Text = "Department", Value = "Department"},
new SelectListItem{Text = "Ministry", Value = "Ministry"}
}, "Select Error Type", new { #style = "border-radius:3px;", #type = "text", #class = "form-control", #placeholder = "Enter Organization Type", #autocomplete = "on" })
#Html.ValidationMessageFor(model => model.NodeDescription, "", new { #class = "alert-error" })
</div>
</div>
<div class="clearfix">
</div>
<br />
<br />
<div class="col-md-12">
<div>
<div class="pull-left">
<input type="submit" id="savenode" value="S A V E" class="btn btn-primary" />
</div>
<div class="pull-right">
<input type="button" id="closePopOver" value="C L O S E" class="btn btn-primary" />
</div>
</div>
</div>
<div class="clearfix">
</div>
}
</div>
</div>
View
<div class="col-md-12" style="margin:100px auto;">
<div class="modal fade in" id="modalAddNode" role="dialog" aria-hidden="true">
#Html.Partial("_AddNode")
</div>
<div class="col-md-12">
<div class="panel panel-primary">
<div class="panel-heading">Ministries, Departments and Agencies -: [ Add MDA and its Members ]</div>
<div class="panel-body">
<div id="tree"></div>
<div class="clearfix">
</div>
<br />
<div>
<button id="btnDeleteNode" data-toggle="modal" class='btn btn-danger'> Delete Node <span class="glyphicon glyphicon-trash"></span> </button>
<button id="btnpopoverAddNode" data-toggle="modal" class='btn btn-warning'> Add Node <span class="glyphicon glyphicon-plus"></span> </button>
</div>
</div>
</div>
</div>
Scipts
#section Scripts {
#System.Web.Optimization.Scripts.Render("~/bundles/jqueryval")
<script src="#Url.Content("~/Scripts/conditional-validation.js")" type="text/javascript"></script>
<script src="~/Scripts/Gijgo/gijgo.js"></script>
<link href="http://code.gijgo.com/1.3.0/css/gijgo.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
//'Hierarchy/GetHierarchy'
$(document).ready(function () {
var Usertree = "";
var tree = "";
$.ajax({
type: 'get',
dataType: 'json',
cache: false,
url: '/Mda/GetHierarchy',
success: function (records, textStatus, jqXHR) {
tree = $('#tree').tree({
primaryKey: 'MDA_ID',
dataSource: records,
dragAndDrop: true,
checkboxes: true,
iconsLibrary: 'glyphicons',
//uiLibrary: 'bootstrap'
});
Usertree = $('#Usertree').tree({
primaryKey: 'MDA_ID',
dataSource: records,
dragAndDrop: false,
checkboxes: true,
iconsLibrary: 'glyphicons',
//uiLibrary: 'bootstrap'
});
tree.on('nodeDrop', function (e, MDA_ID, PARENT_MDA_ID) {
currentNode = MDA_ID ? tree.getDataById(MDA_ID) : {};
console.log("current Node = " + currentNode);
parentNode = PerentId ? tree.getDataById(PARENT_MDA_ID) : {};
console.log("parent Node = " + parentNode);
if (currentNode.PARENT_MDA_ID === null && parentNode.PARENT_MDA_ID === null) {
alert("Parent node is not droppable..!!");
return false;
}
// console.log(parent.HierarchyLevel);
var params = { MDA_ID: MDA_ID, PARENT_MDA_ID: PARENT_MDA_ID };
$.ajax({
type: "POST",
url: "/Mda/ChangeNodePosition",
data: params,
dataType: "json",
success: function (data) {
$.ajax({
type: "Get",
url: "/Mda/GetHierarchy",
dataType: "json",
success: function (records) {
Usertree.destroy();
Usertree = $('#Usertree').tree({
primaryKey: 'MDA_ID',
dataSource: records,
dragAndDrop: false,
checkboxes: true,
iconsLibrary: 'glyphicons',
//uiLibrary: 'bootstrap'
});
}
});
}
});
});
$('#btnGetValue').click(function (e) {
var result = Usertree.getCheckedNodes();
if (result == "") { alert("Please Select Node..!!") }
else {
alert("Selected Node id is= " + result.join());
}
});
//delete node
$('#btnDeleteNode').click(function (e) {
e.preventDefault();
var result = tree.getCheckedNodes();
if (result != "") {
$.ajax({
type: "POST",
url: "/Mda/DeleteNode",
data: { values: result.toString() },
dataType: "json",
success: function (data) {
alert("Deleted successfully ");
window.location.reload();
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
},
});
}
else {
alert("Please select Node to delete..!!");
}
});
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
}
});
// show model popup to add new node in Tree
$('#btnpopoverAddNode').click(function (e) {
e.preventDefault();
$("#modalAddNode").modal("show");
});
//Save data from PopUp
$(document).on("click", "#savenode", function (event) {
event.preventDefault();
$.validator.unobtrusive.parse($('#formaddNode'));
$('#formaddNode').validate();
if ($('#formaddNode').valid()) {
var formdata = $('#formaddNode').serialize();
// alert(formdata);
$.ajax({
type: "POST",
url: "/Mda/AddNewNode",
dataType: "json",
data: formdata,
success: function (response) {
// $("#modalAddNode").modal("hide");
window.location.reload();
},
error: function (response) {
alert('Exception found');
// $("#modalAddNode").modal("hide");
window.location.reload();
},
complete: function () {
// $('.ajax-loader').css("visibility", "hidden");
}
});
}
});
//Close PopUp
$(document).on("click", "#closePopup", function (e) {
e.preventDefault();
$("#modalAddNode").modal("hide");
});
$('.rbtnnodetype').click(function (e) {
if ($(this).val() == "Pn") {
$('.petenddiv').attr("class", "petenddiv hidden");
$("#ParentName").val("");
}
else {
$('.petenddiv').attr("class", "petenddiv");
}
});
});
</script>
}
As shown above, what I have created can only do one level node. I want want to create multi-level.Whereby, a child will be a parent to other children.
Please how do I achieve this.
You can see some ASP.NET examples about this at https://github.com/atatanasov/gijgo-asp-net-examples/tree/master/Gijgo.Asp.NET.Examples
Please use our examples in order to achieve that.

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

Resources