How to get value of KendoUI TreeView - asp.net-mvc-4

Firstable sorry for my English. I've problem with KendoUI TreeView control on ASP.NET MVC4.
<div class="treeview-back">
#(Html.Kendo().TreeView()
.Name("treeview-left")
.DragAndDrop(true)
.Events(ItemAction)
.BindTo(Model)
)
I got treeview and binded event OnDrop:
function OnDrop(e) {
dropped = GetValueFromTags(e.destinationNode.innerHTML);
inDrag = !inDrag;
OnHover();
e.setValid(e.valid && id > 10000);
if (e.valid && id > 10000) {
var webMethod = "/Sitemap/UpdateData";
var data = $("div.treeview-back").find("span.items").text();
//var data = $("div.treeview-back").data("kendoTreeView").dataSource.data();
console.log(data);
$.ajax({
type: "POST",
url: webMethod,
data: data,
contentType: "application/json",
dataType: "json",
converters: {
'text json': true
},
success: function(data) {
},
error: function(data) {
console.log("error: " + data);
}
});
}
}
And my action in Controller:
[HttpPost]
public ActionResult UpdateData(IEnumerable<TreeViewItemModel> data)
{
// some database operations here
return Json(data);
}
I would like to send current state of my treeview to action. Problem is current method is sending null. I was able to send datasource but it was orginal data (that what i binding to control on start), not the current.
Thanks for help,
Łukasz

Related

Error Ajxa call in asp.net xhr.send( options.hasContent && options.data || null )

I tried to so hard to solve it but couldn't.
I got error
xhr.send( options.hasContent && options.data || null )
while saving data this error shows in Jquery.js.
Code is working perfectly in debug mode in vs 2022. I can save data in debug mode. But when
I compile (Publish) this project. I hosted in IIS and every things working perfectly but not in this form When I try to post data then I got same error.
I tried to send header but not working..
var token =
$('input:hidden[name="__RequestVerificationToken"]').val();
headers: { RequestVerificationToken: token },
var detailsList = new Array();
var detailsObj = new Object();
$("#tblDropItem tbody tr").each(function () {
let row = $(this);
let itemId = Number(row.find('.item_detl').attr('purItem_id'));
detailsObj = {
ItemId: itemId,
ItemName: row.find(".item_detl").val(),
Quantity: parseFloat(row.find(".quantity_detl").val()),
UnitId: Number(row.find('.unit_detl').attr('unit_id')),
Rate: parseFloat(row.find(".rate_detl").val()),
Amount: parseFloat(row.find(".amount_detl").val()),
}
if (detailsObj.ItemName) {
detailsList.push(detailsObj);
}
});
var postData = {
PurMode: $("#PurMode").val(),
PurDate: $("#PurDate").val(),
SupId: $("#SupId option:selected").val(),
SubAmount: parseFloat($("#SubAmount").val()),
Discount: parseFloat($("#DiscountPercent").val()),
DiscountAmount: parseFloat($("#Discount").val()),
TotalAmount: parseFloat($("#TotalAmount").val()),
Remarks: $("#Remarks").val(),
Taxable: parseFloat($("#Taxable").val()),
VatAmount: parseFloat($("#VatAmount").val()),
VATable: parseFloat($("#VATable option:selected").val())
PurchaseDetailItemList: detailsList,
__RequestVerificationToken: $("input[name=__RequestVerificationToken]").val(),
}
$.ajax({
type: "POST",
url: "/Purchase/SavePurchase",
dataType: 'JSON',
data: postData,
async:false,
success: function (result) {
toastr.success('Data Saved Successfully');
window.location = "#Url.Content("~/Purchase/Index")";
},
error: function (result) {
toastr.error("Cann't Save Data.");
}
});
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult SavePurchase(PurchaseDTO model)
{
if (!ModelState.IsValid)
{
return Json("error");
}
//code...
}
Can you please suggest any mistake..
Everything is correct, maybe you have hosted incorrectly in iis, make sure your post url is valid in console.

ASP.NET Core Post Action returns null

I have a simple controller method that should return a JSON result but returns null. I need to call it using jQuery $.ajax. I tested it using Postman and it does return null. I am not sure what I am doing wrong.
I tested it with Postman using the following JSON data and it returns null:
{ "id": 2 }
Here is the controller method:
// Post: Contact
[HttpPost, ActionName("GetContact")]
public JsonResult GetContactPost([FromBody] long id)
{
var contact = _context.Contact.SingleOrDefault(m => m.ContactId == id);
return Json(contact);
}
In my application I am using the following JavaScript and it returns null as well:
function GetContact(id) {
$.ajax({
type: "POST",
url: "#Url.Action("GetContact","Contacts")",
data: { id: id },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("id: " + id + " result: " + result);
},
failure: function (response) {
alert(response.d);
}
});
}
I figured it out. The parameter has to be a model or view model object.
// Post: Contact
[HttpPost, ActionName("GetContact")]
public JsonResult GetContactPost([FromBody] ContactVM findContact)
{
var contact = _context.Contact.SingleOrDefault(m => m.ContactId == findContact.Id);
return Json(contact);
}

How to load message in real time to a viewer in MVC 4 framework

I'm creating a MVC 4 .NET/C# project to do data loading automatically. When insert new record to database, I want to display a line of message in the viewer in real time. So it would be something like
Record 1 has been loaded successfully!
Record 2 has been loaded successfully!
Record 3 has been loaded successfully!
Record 4 has been loaded successfully!
....
Is there a way to do this?
Thank you for any idea.
Of course. First at all you should write a method which returns numer of records. On the loading page you can use that method to receive number of records f.ex:
Controller:
public ActionResult CountRecords()
{
int records = repository.CountRecords();
return JavaScript(SimpleJsonSerializer.Serialize(records.ToString());
}
public ActionResult LoadRecord(int number)
{
repository.LoadRecord(number);
return JavaScript(SimpleJsonSerializer.Serialize("Success");
}
.cshtml
<script type="text/javascript">
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "#Url.Action("CountRecords", "Controller")",
success: function (response) {
var rows = response.replace('\"', '');
for (i = 1; i <= rows; i++)
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: i,
url: "#Url.Action("LoadRecord", "Controller")",
success: function (response) {
var status = response.replace('\"', '');
if (status == 'Success')
$('.messages').append('Record ' + i + ' has been loaded successfully!');
}
});
}
}
});
</script>
Of course it would take more time than in 1 call to controller, but it will works. I don't know if there is possibility to make realtime interface without calling controller many times.
Saving items can be done same as loading.
Regards.

MVC4 .Net , controls on hidden fields

I wonder if it's possible to have controls (dataanotation) on hidden fields (HiddenFor or hidden EditorFor) ?
I don't think so, but we never know.
There are a lot of posts on how to hide EditorFor such as :
TextBoxFor vs EditorFor, and htmlAttributes vs additionalViewData
In my case,in a view I have a jquery call to a WCF REST service, that in success case fill my EditorFor. I would like that the Required DataAnotation to be applied on that EditorFor, would it be possible ?
I think that as long as the EditorFor is invisible the DataAnotation cannot be applied. Would it have a way to apply the DataAnotation on the hidden EditorFor ?
Here is the code :
To hide the EditorFor :
#Html.EditorFor(model => model.VilleDepart, "CustomEditor", new {style = "display:none;" })
The CustomEditor :
#{
string s = "";
if (ViewData["style"] != null) {
// The ViewData["name"] is the name of the property in the addtionalViewData...
s = ViewData["style"].ToString();
}
}
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { style = s })
the model :
string _VilleDepart;
[Required]
[Display(Name = "Ville Départ")]
public string VilleDepart
{
get
{
if (Commune != null) {
return Commune.Commune1;
}
return _VilleDepart;
}
set {
_VilleDepart = value;
}
}
The JQuery call to WCF REST Service :
$(document).ready(function () {
$([document.getElementById("IVilleDepart"), document.getElementById("IVilleArrivee")]).autocomplete({
source: function (request, response) {
$.ajax({
cache: false,
type: "GET",
async: false,
dataType: "json",
url: GetSearchCommunetURl + "(" + request.term + ")",
success: function (data) {
//alert(data);
response($.map(data, function (item) {
return {
label: item['Commune'] + ' (' + item['CodePostal'] + ')',
val: item
}
}))
},
error: function (response) {
alert("error ==>" + response.statusText);
},
failure: function (response) {
alert("failure ==>" + response.responseText);
}
});
},
select: function (e, i) {
if (e.target.id == "IVilleDepart") {
VilleDepart = i.item.val;
EVilleDepart.value = VilleDepart.Commune;
ECodePostalDepart.value = VilleDepart.CodePostal;
ECodeINSEEDepart.value = VilleDepart.CodeINSEE;
}
if (e.target.id == "IVilleArrivee") {
VilleArrivee = i.item.val;
EVilleArrivee.value = VilleArrivee.Commune;
ECodePostalArrivee.value = VilleArrivee.CodePostal;
ECodeINSEEArrivee.value = VilleArrivee.CodeINSEE;
}
},
minLength: 2
});
});
If I don't hide the EditorFor I can see it is correctly filled after the WCF REST service call and the Required DataAnotation is applied.
There are other way to hide the EditorFor, for instance to apply the style='width:0px;height:0px'
It hides but disable the Required DataAnotation,
if I apply the style='width:0px;height:1px', we don't see a lot of the EditorFor but the Required DataAnotation is active.
I've seen an answer at http://www.campusmvp.net/blog/validation-of-hidden-fields-at-the-client-in-asp-net-mvc
(but it seems i had badly searched precedently, the validation of hidden field is treated in some blogs and sites).
To active the validation of hidden fields, you just have to add this little javascript line :
$.validator.setDefaults({ ignore: null });
and it works !
Apparently it doesn't work with mvc2, but works since mvc3.

Delete method with array type as parameter showing null value

I am calling web-api method delete all with array type parameter, showing the value null. why?
I am passing data like : data: "ArrMenuId"+ JsArrayMenuId,
function performalldeletemenu()
{
if (confirm('Are you sure you want to delete this menu?'))
{
var JsArrayMenuId = new Array();
$("input:checked").each(function ()
{
//console.log($(this).val()); //works fine
JsArrayMenuId.push($(this).val());
});
alert(JsArrayMenuId);
$.ajax({
url: '/api/MenuWebApi/DeleteAllMenu/',
type: 'DELETE',
contentType: 'application/json; charset=utf-8',
data: "ArrMenuId"+ JsArrayMenuId,
success: function (data)
{
if (data.Success == true)
{
//GetMenuList();
}
},
error: function (xhr, textStatus, errorThrown)
{
//window.location = JsErrorAction;
},
headers:
{
'RequestVerificationToken': JsTokenHeaderValue
}
});
}
return false;
}
public HttpResponseMessage DeleteAllMenu(Array ArrMenuId)
{
}
Here ArrMenuId is showing null values.
if any one have solution, please let me know.
Try changing
data: "ArrMenuId"+ JsArrayMenuId,
to
data: {ArrMenuId : JsArrayMenuId.join()}
and changing
public HttpResponseMessage DeleteAllMenu(Array ArrMenuId)
to
public HttpResponseMessage DeleteAllMenu(string ArrMenuId)
I don't think javascript array will translate easily into a c# array and by changing it to this you are instead passing a string. Once you have this comma delimited string you can make it into an array in your c#