how can I get the checkbox checked Item from grid using jquery - javascript

I have got two kendo ui grids (parent grid , child grid) and i have got check box column on parent grid if i click on the checkbox in row in grid, I need to get the corresponding row data and i need to do moving that selected row data to another grid when click on button for that I have implemented button clikc like this ...
For that purpose I have done like this ....
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(document).ready(function ()
{
$('#btnMove').click(function() {
('#GridParent').on("click", "td", function (e) {
var selectedTd = $(e.target).closest("td");
var grdChkBox = selectedTd.parents('tr').find("td:first").next("td").find('input:checkbox');
//grdChkBox.prop('checked', !grdChkBox.prop('checked'));
if(grdChBox.Checked)
{
// here I need to get the checkbox selected item row data
// i dont know it is the correct way to get the item pls correct me
}
var sourcegrid = $('#GridParent').data('kendoGrid');
var destinationgrid = $('#ChildGrid').data('kendoGrid');
var checkeditem =
});
</script>
#model IEnumerable<KendoSampleMVCApp.Models.StudentDetails>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm())
{
#(Html.Kendo().Grid<KendoSampleMVCApp.Models.StudentDetails>()
.Name("GridParent")
.Columns(columns => {
columns.Bound(p => p.studentclass).HeaderTemplate("<input id='selectall' class='chkbx' type='checkbox' onclick='ToggleChkBox(this.checked);' />").ClientTemplate("<input id='checkbox' onclick='grdChkBoxClick(this); ' class='chkbxq' type='checkbox' />").Sortable(false).Filterable(false).Width(30);
columns.Bound(p => p.studentId).Filterable(false).Width(90);
columns.Bound(p => p.studentName).Filterable(false).Width(90);
columns.Bound(p => p.StudentBranch).Filterable(false).Width(90);
})
.Pageable()
.Sortable()
.Scrollable()
.Filterable()
.Resizable(resize => resize.Columns(true))
.Reorderable(reorder => reorder.Columns(true))
.Selectable(s => s.Mode(GridSelectionMode.Multiple))
.HtmlAttributes(new { style = "height:250px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("Orders_Read", "StudentDtls"))
)
)
<input id="btnMove" type="button" value="Move" />
// second grid .......
I am not sure about the data how can i get when the check box selected
would any one pls help on this ...
Many Thanks .....

In checkbox check select row bind in new grid from controller side. Hope it's working for you
View
#{
ViewBag.Title = "GridListView";
}
<h2>
GridListView</h2>
<script src="~/Script/Jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="~/Script/jquery-ui-1.8.20.min.js" type="text/javascript"></script>
<script src="#Url.Content("~/Script/kendo.all.min.js")" type="text/javascript"></script>
<script src="~/Script/kendo.web.min.js" type="text/javascript"></script>
<script src="~/Script/kendo.aspnetmvc.min.js" type="text/javascript"></script>
<link href="~/Content/kendo.common.min.css" rel="stylesheet" type="text/css" />
<link href="~/Content/kendo.default.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
$('#grid12').on("click", ".chkbxq", function (e) {
var selectedTd = $(this).is(':checked');
var rowIndex = $(this).parent().index();
var cellIndex = $(this).parent().parent().index();
var grid = $("#grid12").data("kendoGrid");
var datatItem = grid.dataItem(grid.tbody.find('tr:eq(' + cellIndex + ')'));
if (selectedTd == true) {
sampleItem = datatItem.SampleItems;
sampleCode = datatItem.SampleCode;
sampledescription = datatItem.SampleDescription;
datavalueitem = sampleItem + "--" + sampleCode + "--" + sampledescription;
$.ajax({
url: '#Url.Action("NewGridView", "Test")',
type: "Post",
data: { sampleItem: sampleItem, sampleCode: sampleCode, sampledescription: sampledescription },
dataType: 'json',
success: function (result) {
debugger;
$("#mygrid").val(null);
var customDataList = $('#grid');
customDataList.empty();
customDataList.append(result.Data);
customDataList.append(result.Data);
$("#divasd").kendoGrid({
dataSource: result,
sortable: true,
pageable: {
refresh: true,
pageSizes: true
},
columns: [
{
field: "SampleDescription",
width: 90,
}, {
field: "SampleCode",
width: 90,
}, {
width: 100,
field: "SampleItems"
}
]
});
}
});
}
});
});
</script>
#using (Html.BeginForm("GridListView", "Test", FormMethod.Post))
{
<input id="Submit1" type="button" value="SubmitValue" />
#(Html.Kendo().Grid<TwoModelInSinglePageModel.SampleModel>()
.Name("grid12")
.Columns(columns =>
{
columns.Bound(p => p.studentclass).HeaderTemplate("<input id='selectall' class='chkbxq' type='checkbox' />").ClientTemplate("<input id='checkbox' class='chkbxq' type='checkbox' />");
columns.Bound(p => p.SampleDescription);
columns.Bound(p => p.SampleCode);
columns.Bound(p => p.SampleItems);
})
.AutoBind(true) // here I am disabling automatic binding at page load
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Read", "Test"))
)
)
<br />
<div id="divasd">
</div>
}
Controller
public JsonResult NewGridView(string sampleItem, string sampleCode, string sampledescription)
{
List<SampleModel> sampleAddList = new List<SampleModel>();
SampleModel sampleAdd = new SampleModel();
sampleAdd.SampleCode = sampleCode;
sampleAdd.SampleDescription = sampledescription;
sampleAdd.SampleItems = sampleItem;
sampleAddList.Add(sampleAdd);
var result = sampleAddList;
return Json(result, JsonRequestBehavior.AllowGet);
}
This bind grid from Controller side
Model
public class SampleModel
{
public bool studentclass { get; set; }
public string SampleDescription { get; set; }
public string SampleCode { get; set; }
public string SampleItems { get; set; }
}

Related

How to update 2 dropdowns based on primary dropdown?

I'm trying to update 2 dependent dropdowns simultaneously based on the value of the primary dropdown. Is it possible, if yes, what's wrong in my code? Correct, please.
Maybe it's better to use ASP.NET cascading dropdowns possibilites? If yes, how to do it with 3 dropdowns ?
View
#model RKB.Models.CountryStateViewModel
<br /><br/>
#using (Html.BeginForm("Index", "Home"))
{
<div class="container">
<div class="form-group">
#if (ViewBag.CountryList != null)
{
#Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "Выберите страну", new { #class = "form-control" })
}
</div>
<div class="form-group">
#Html.DropDownListFor(model => model.StateId, new SelectList(" "), "Выберите штат", new { #class = "form-control" })
</div>
<div class="form-group">
#Html.DropDownListFor(model => model.PriceId, new SelectList(" "), "Выберите цену", new { #class = "form-control", #style = "display:none" })
</div>
<button type="submit">Send</button>
</div>
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
$.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
$("#StateId").empty();
$.each(data, function (index, row) {
$("#StateId").append("<option value='" + row.StateId + "'>" + row.StateName + "</option>")
});
});
})
});
$(document).ready(function () {
$("#StateId").change(function () {
$.get("/Home/PriceList", { StateId: $("#StateId").val() }, function (data) {
$("#PriceId").empty();
$.each(data, function (index, row) {
$("#PriceId").append("<option value='" + row.PriceId + "'>" + row.Price1 + "</option>")
});
});
})
});
</script>
Controller
public class HomeController : Controller
{
RKBEntities db = new RKBEntities();
public ActionResult Index()
{
List<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
return View();
}
[HttpPost]
public ActionResult Index(CountryStateViewModel csm)
{
return View();
}
public JsonResult GetStateList(int CountryId)
{
db.Configuration.ProxyCreationEnabled = false;
List<State> StateList = db.States.Where(x => x.CountryId == CountryId).ToList();
return Json(StateList, JsonRequestBehavior.AllowGet);
}
public JsonResult GetPriceList(int StateId)
{
db.Configuration.ProxyCreationEnabled = false;
List<Price> PriceList = db.Prices.Where(x => x.StateId == StateId).ToList();
return Json(PriceList, JsonRequestBehavior.AllowGet);
}
}
You have used the wrong property json, my friend.
For example: row.StateId => row.stateId.
Just try to modify following like this:
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
$.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
$("#StateId").empty();
$.each(data, function (index, row) {
$("#StateId").append("<option value='" + row.stateId + "'>" + row.stateName + "</option>")
});
});
})
});
$(document).ready(function () {
$("#StateId").change(function () {
$.get("/Home/PriceList", { StateId: $("#StateId").val() }, function (data) {
$("#PriceId").empty();
$.each(data, function (index, row) {
$("#PriceId").append("<option value='" + row.priceId + "'>" + row.price1 + "</option>")
});
});
})
});
</script>
Hope to help, my friend :))

Cascading dropdown list does not bind data to the 2nd dropdown

I have a main view. Once the posting is done, it will render a partial view in the main view.
My partial view has a cascading dropdown list that changes the 2nd DropdownList items based on the selected value from the 1st DropdownList.
Here is my Dropdown in my Partial View.
#model MigratingDB.Models.ViewModel
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<div>
#Html.DropDownListFor(m => m.DropdownViewModel.SelectedValue1,
Model.DropdownViewModel.List1, "Select",htmlAttributes: new { #class = "form-control", #id = "ddl1" })
</div>
<div>
#Html.DropDownListFor(m => m.DropdownViewModel.SelectedValue2,
Model.DropdownViewModel.List2 = new SelectList(Enumerable.Empty<SelectListItem>()), "Select",
htmlAttributes: new { #class = "form-control", #id = "ddl2" })
</div>
The script I tried based from this.
<script>
$(function () {
$('#ddl1').change(function () {
$("#ddl2").empty();
var selectedValue = $(this).val();
$.ajax({
url: '#Url.Action("Getddl2Items", "Controller")',
type: "POST",
dataType: 'json',
data: { id: selectedValue },
success: function (value) {
$.each(value, function (i, val) {
$("#ddl2").append('<option value="' + val.Value + '">' +
val.Text + '</option>');
});
},
error: function (ex) {
alert('Failed' + ex);
},
});
});
});
</script>
In my Controller:
[HttpPost]
public ActionResult Foo (ViewModel vm)
{
// Dropdownlist
var list1 = // get items frop ddl1
vm.DropdownViewModel.List1= new SelectList(list1, "Value", "Text");
return PartialView("_PartialView", vm);
}
// Get ddl2 Items
public JsonResult Getddl2Items (int id)
{
var ViewModel = new ViewModel();
var list2= // get ddl2 items from the database
ViewModel.DropdownViewModel.List2= new SelectList(list2, "Value", "Text");
return Json(ViewModel.DropdownViewModel.List2, JsonRequestBehavior.AllowGet);
}
Every time I tried to select a value from the ddl1, it errors and show
Failed [object Object].
What causes this?
This is a long post that I tested and works. Since it is long, you can pick out the parts you need. Let's work together to figure out why it is not working for you.
This will be your table and data creation:
--Use your database name instead of Breaz
USE [Breaz]
GO
/****** Object: Table [dbo].[tblCity] Script Date: 7/17/2017 9:46:31 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblCity](
[Cityid] [int] NOT NULL,
[CityName] [nvarchar](50) NULL,
[stateid] [int] NOT NULL
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[tblState] Script Date: 7/17/2017 9:46:31 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblState](
[stateid] [int] NOT NULL,
[statename] [nvarchar](50) NULL,
PRIMARY KEY CLUSTERED
(
[stateid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT [dbo].[tblCity] ([Cityid], [CityName], [stateid]) VALUES (1, N'Phoenix', 1)
INSERT [dbo].[tblCity] ([Cityid], [CityName], [stateid]) VALUES (2, N'Las Angeles', 2)
INSERT [dbo].[tblState] ([stateid], [statename]) VALUES (1, N'Arizona')
INSERT [dbo].[tblState] ([stateid], [statename]) VALUES (2, N'California')
ALTER TABLE [dbo].[tblCity] WITH CHECK ADD FOREIGN KEY([stateid])
REFERENCES [dbo].[tblState] ([stateid])
GO
Create your edmx, by going through visual studio wizard.
Create your view model:
//user your namespace
namespace Testy20161006.Models
{
public class Registration
{
[Required(ErrorMessage = "Enter State")]
public string State { get; set; }
[Required(ErrorMessage = "Enter City")]
public string City { get; set; }
}
}
Your controller/classes:
public class HomeController : Controller
{
public JsonResult getCity(int id)
{
//use your dbcontext name from edmx wizard
using (BreazEntities33 objEF = new BreazEntities33())
{
var ddlCity = objEF.tblCities.Where(x => x.stateid == id).ToList();
List<SelectListItem> licities = new List<SelectListItem>();
licities.Add(new SelectListItem { Text = "--Select State--", Value = "0" });
if (ddlCity != null)
{
foreach (var x in ddlCity)
{
licities.Add(new SelectListItem { Text = x.CityName, Value = x.Cityid.ToString() });
}
}
return Json(new SelectList(licities, "Value", "Text", JsonRequestBehavior.AllowGet));
}
}
[HttpPost]
public ActionResult IndexStackOverflow(Registration registration)
{
//put breakpoint here to see values coming back from view
return View(registration);
}
//use your name of action that starts the process, named in routeconfig.cs
public ActionResult IndexStackOverflow()
{
bindState();
return View();
}
public void bindState()
{
//use your dbcontext name from edmx wizard
using (BreazEntities33 objEF = new BreazEntities33())
{
var state = objEF.tblStates.ToList();
List<SelectListItem> li = new List<SelectListItem>();
li.Add(new SelectListItem { Text = "--Select State--", Value = "0" });
foreach (var m in state)
{
li.Add(new SelectListItem { Text = m.statename, Value = m.stateid.ToString() });
ViewBag.state = li;
}
}
}
Here is your view:
#model Testy20161006.Models.Registration
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>IndexStackOverflow</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#State").change(function () {
$("#City").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("getcity")',
dataType: 'json',
data: { id: $("#State").val() },
success: function (city) {
$.each(city, function (i, city) {
$("#City").append('<option value="'
+ city.Value + '">'
+ city.Text + '</option>');
});
},
error: function (ex) {
alert('Failed.' + ex);
}
});
return false;
})
});
</script>
</head>
<body>
#using (Html.BeginForm())
{
<div class="container">
<div class="row">
<div class="form-group">
#Html.LabelFor(model => model.State, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.State, ViewBag.state as List<SelectListItem>, new { style = "width: 200px;" })
#Html.ValidationMessageFor(model => model.State, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="form-group">
#Html.LabelFor(model => model.City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.City, new SelectList(string.Empty, "Value", "Text"), "--Select City--", new { style = "width:200px" })
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div><input type="button" value="submit" /></div>
}
</body>
</html>
Here is an example that returns Json value from a SelectListItem in a ViewModel.
public class ReturnJsonVM
{
public List<SelectListItem> licities = new List<SelectListItem>();
}
public class HomeController : Controller
{
//use your name of action that starts the process, named in routeconfig.cs
public string IndexStackOverflow()
{
using (BreazEntities33 objEF = new BreazEntities33())
{
var ddlCity = objEF.tblCities.Where(x => x.stateid == 1).ToList();
List<SelectListItem> licities = new List<SelectListItem>();
ReturnJsonVM returnJsonVM = new ReturnJsonVM();
if (ddlCity != null)
{
foreach (var x in ddlCity)
{
returnJsonVM.licities.Add(new SelectListItem { Text = x.CityName, Value = x.Cityid.ToString() });
}
}
string json = JsonConvert.SerializeObject(returnJsonVM.licities);
//put your break point here to see example that return Json value from SelectListItem in ViewModel
return json;
}
}

I want to cascade multiple Dropdown lists using mvc 4 razor in ASP.NET

In this MVC application I've created cascading dropdown list i.e it will first populate countries list and after selecting country jquery's onchange event is called which will fetch the further states from the controller which further gets those data by edmx entity model in database.i have used ajax request to call the JSON method in this.After selecting states the new dropdown list would get activated for selecting Cities.Whenever I select countries from the drop down an alertbox pops out and says states retrieving failed.[object][object] also I didn't create relationship between tables as foreign key is that necessary
Location Controller:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication3.Controllers
{
public class LocationController : Controller
{
//
// GET: /Location/
public ActionResult Index()
{
TestDBEntities db = new TestDBEntities();
ViewBag.Country = new SelectList(db.tblCountries, "CountryID", "CountryName");
return View();
}
public JsonResult GetState(string id)
{
List<SelectListItem> states = new List<SelectListItem>();
var stateList = this.Getstatevalue(Convert.ToInt32(id));
var stateData = stateList.Select(m => new SelectListItem()
{
Text = m.StateName,
Value = m.StateID.ToString(),
});
return Json(stateData, JsonRequestBehavior.AllowGet);
}
public IList<tblState> Getstatevalue(int CountryId)
{
TestDBEntities db = new TestDBEntities();
return db.tblStates.Where(m => m.CountryID == CountryId).ToList();
}
public JsonResult GetCity(string id)
{
List<SelectListItem> cities = new List<SelectListItem>();
var cityList = this.Getcityvalue(Convert.ToInt32(id));
var cityData = cityList.Select(m => new SelectListItem()
{
Text = m.CityName,
Value = m.CityID.ToString(),
});
return Json(cityData, JsonRequestBehavior.AllowGet);
}
public IList<tblCity> Getcityvalue(int StateId)
{
TestDBEntities db = new TestDBEntities();
return db.tblCities.Where(m => m.StateID == StateId).ToList();
}
}
}
Index.cshtml view
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>EmployeeData</legend>
<div class="editor-label">
#Html.Label("Country")<br />
</div>
<div>
#Html.DropDownList("Country", ViewBag.Country as SelectList, "-- Please Select a Country --", new { style = "width:150px", #id = "Country" })
</div>
<div class="editor-label">
<br />
#Html.Label("State")<br />
</div>
<div>
#Html.DropDownList("State", new SelectList(string.Empty, "Value", "Text"), "-- Please select a State --",
new { style = "width:150px", #class = "dropdown1" })
</div>
<div class="editor-label">
<br />
#Html.Label("City")<br />
</div>
<div>
#Html.DropDownList("City", new SelectList(string.Empty, "Value", "Text"), "-- Please select a city --",
new { style = "width:150px", #class = "dropdown2", #id = "City" })
</div>
<p>
<input type="button" onclick="ddlInsert()" value="Submit" />
</p>
</fieldset>
}
javascript code :
<script type="text/javascript">
$(document).ready(function () {
// this is Country Dropdown Selectedchange event
$("#Country").change(function () {
$("#State").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("Getstates")', // here we are Calling json method
dataType: 'json',
data: { id: $("#Country").val() },
// Get Selected Country ID.
success: function (states) {
$.each(states, function (i, state) {
$("#State").append('<option value="' + state.Value + '">' +
state.Text + '</option>');
});
},
error: function (ex) {
alert(' states retrieving fail.' + ex);
}
});
return false;
})
$("#State").change(function () {
$("#City").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetCities")', // here we are Calling json method
dataType: 'json',
data: { id: $("#State").val() },
// Get Selected Country ID.
success: function (cities) {
$.each(cities, function (i, city) {
$("#City").append('<option value="' + city.Value + '">' +
city.Text + '</option>');
});
},
error: function (ex) {
alert(' city retrieving fail.' + ex);
}
});
return false;
})
});
</script>
When I select a country in it No state gets loaded or populated into the dropdown list for states.

Asp.net MVC Client side validation not working,it still submit the form

#model MVC_Practice2.Models.MyOrder
#{
Layout = null;
Html.EnableClientValidation();
}
#using MVC_Practice2.Models;
<script type="text/javascript">
$(function(){
//$.validator.unobtrusive.parse("#order_detail");
jQuery.validator.unobtrusive.parse();
alert("load finished");
});
</script>
#using (Html.BeginForm("Update", "Order", FormMethod.Post, new { id = "order_detail" })) {
<input type="hidden" name="Id" value="#Model.Id">
<table class="dv-table" style="width:100%;border:1px solid #ccc;padding:5px;margin-top:5px;">
<tr>
<td>#Html.LabelFor(x=>x.OrderDate)</td>
<td>#Html.TextBoxFor(x => x.OrderDate, new { #class = "easyui-datetimebox", style = "width:200px" })
#Html.ValidationMessageFor(x=>x.OrderDate)
</td>
<td>Status</td>
<td>
#if (Model.Status.Trim() == "Pending")
{
#Html.RadioButtonFor(x => x.Status, "P", new {#checked="checked" })<text>Pending</text>
}
else
{
#Html.RadioButtonFor(x => x.Status, "P", new { style = "width:100px" })<text>Pending</text>
}
#Html.RadioButtonFor(x => x.Status, "Cancelled", new { style = "width:100px" })<text>Cancelled</text>
#Html.RadioButtonFor(x => x.Status, "Delivered", new { style = "width:100px" })<text>Delivered</text></td>
</tr>
<tr>
<td>CustomerName</td>
<td colspan="3">
#Html.DropDownListFor(x => x.CustomerId, ViewBag.sl as IEnumerable<SelectListItem>)
</td>
</tr>
</table>
<div style="padding:5px 0;text-align:right;padding-right:30px">
<input type="submit" class="easyui-linkbutton" iconcls="icon-save" plain="true">
Cancel
</div>
#Html.ValidationSummary()
}
This is my View code,this is a AJAX load of the form,when I click the submit button,it directly submit to the backend with out showing me the clientside error message as expected ,I have already add the jquery.validate.min.js and jquery.validate.unobtrusive.min.js in my _Layout.cshtml file shown as below
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<script src="~/Scripts/jquery-1.11.3.min.js"></script>
<script src="~/Scripts/jsrender.min.js"></script>
<script src="~/Scripts/jquery.easyui-1.4.3.min.js"></script>
<script src="~/Scripts/datagrid-detailview.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<link href="~/Content/themes/black/easyui.css" rel="stylesheet" />
<link href="~/Content/themes/icon.css" rel="stylesheet" />
<title>#ViewBag.Title</title>
#RenderSection("headsection", required: false)
</head>
<body>
#RenderBody()
</body>
</html>
The following is my Model code
namespace MVC_Practice2.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
public partial class MyOrder
{
public int Id { get; set; }
[DisplayName("高端时间")]
[Required(ErrorMessage = "不能为空")]
public System.DateTime OrderDate { get; set; }
[StringLength(4, ErrorMessage = "太长了")]
public string Status { get; set; }
public int CustomerId { get; set; }
public virtual MyCustomer MyCustomer { get; set; }
}
}
And the following is my MainPage which use easyui ajax load that partial form view as I mentioned in the top
#{
ViewBag.Title = "EasyUI_Index";
}
<h2>EasyUI_Index</h2>
#section headsection
{
<script type="text/javascript">
function formatterdate(val, row) {
if (val != null) {
var date = new Date(parseInt(val.replace("/Date(", "").replace(")/", ""), 10));
var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
// var milliseconds = date.getMilliseconds();
//return date.getFullYear() + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
//当前需要这种时间格式MM/dd/yyyy hh:mm:ss
return month + "/" + day + "/" +date.getFullYear()+" "+ hours + ":" + minutes + ":" + seconds;
}
}
$(function () {
$("#tbList").datagrid({
title: 'DataGrid - DetailView',
view: detailview,
fitColumns: true,
nowrap: false,
detailFormatter: function (index, row) {
return '<div class="record_info"></div>';
},
onExpandRow: function(index,row){
var ddv = $(this).datagrid('getRowDetail', index).find('div.record_info');
ddv.panel({
border:false,
cache:true,
href: '/Order/Retrieve_Single_Order/' + row.OrderId+"?index="+index,
onLoad:function(){
$('#tbList').datagrid('fixDetailRowHeight', index);
$('#tbList').datagrid('selectRow', index);
$('#tbList').datagrid('getRowDetail',index).find('form').form('load',row);
console.log(row);
//$("#dt_box").datetimebox('setValue', '10/08/1990 23:15:10');
$("#OrderDate").datetimebox('setValue',formatterdate(row.OrderTime,null));
}
});
$('#tbList').datagrid('fixDetailRowHeight',index);
jQuery.validator.unobtrusive.parse();
},
url: "/Order/GetPageList",
width: 700,
height:600,
striped: true,
rownumbers: true,
columns: [[
{ field: "OrderId",width:50},
{ field: 'OrderTime', title: 'OrderTime', formatter: formatterdate, width: 50 },
{ field: 'Status', title: 'Status', width: 50 },
{ field: 'CustomerName', title: 'CustomerName', width: 50 },
]],
toolbar: [{
iconCls: 'icon-edit',
text: 'Edit',
handler: function () { alert('编辑按钮') }
}, '-', {
iconCls: 'icon-remove',
text: 'Delete',
handler: function () {
//$('#tbList').datagrid('deleteRow', 1);// 索引从0开始
//$('#tbList').datagrid('reload');刷新一下
var row = $('#tbList').datagrid('getSelected');
if (!row) {
$.messager.alert('Wrong operation', 'You haven\'t choose row yet ', 'error');
}
else {
$.messager.confirm('Warning', 'Do you want to delele this row?', function (r) {
if (r) {
// delete操作;
alert(row.OrderId);
$.ajax({
type: "POST",
url: "/Order/Del/" + row.OrderId,
success: function (msg) {
$('#tbList').datagrid('reload');
}
});
}
});
}
}
}],
pagination: true,
singleSelect: true,
pageSize: 3,
pageList: [3, 10, 30, 40, 50]
})
})
function cancelItem(index) {
$('#tbList').datagrid('collapseRow', index);
}
</script>
}
<table id="tbList" >
<!--<tr>
<th>DatabaseID</th>
<th>Timestamp</th>
<th>Subject</th>
<th>Verb</th>
<th>Object</th>
</tr>-->
</table>
<style type="text/css">
form {
margin: 0;
padding: 0;
}
.dv-table td {
border: 0;
}
.dv-table input {
border: 1px solid #ccc;
}
</style>
The following is my Controller code
public class OrderController : Controller
{
public VideosEntities db = new VideosEntities();
// GET: Order
public ActionResult Index()
{
return View("EasyUI_Index");
}
[HttpPost]
public ActionResult Update(MyOrder model)
{
if (ModelState.IsValid == false)
{
return Content("Please do not forbid the javascript validation.");
}
else
{
int id = Convert.ToInt32(Request.Params["Id"]);
String datetime = Request.Params["OrderDate"];
String status = Request.Params["Status"];
int customerId = Convert.ToInt32(Request.Params["CustomerId"]);
MyOrder updated_order = (from x in db.MyOrders where x.Id == id select x).FirstOrDefault();
updated_order.OrderDate = Convert.ToDateTime(datetime);
updated_order.Status = status;
updated_order.CustomerId = customerId;
db.SaveChanges();
return Redirect("/Order/Index");
}
}
}
Well, as i already mention, you should place $.validator.unobtrusive.parse("#order_detail"); somewhere in ajaxComplete() handler.
$.validator.unobtrusive.parse(); not working without selector becouse it was written to accept selector #Stephen Muecke already mention it. So you can write like his in All cases
$('body').data('validator', null); //This line drop validators if you already have them in your DOM
$.validator.unobtrusive.parse('body');
Half a year ago i've asked question about validation, it could be interesting to you.

Kendo UI Grid get id of current element javascript

i m using Kendo UI apsnet and i have a Gird with autocomptele as template in 3rd column and i want send data using javascript function "onAutoCompleteX", in this function i want to get id of active autocomplete to send text as parametere to action "GetArticle" but my probleme is how get this id, tried many methods always i get "undefined" or error
#using KendoUIMvcApplication2.Areas.Gescom.Models.Achat
<style>
.k-widget .templateCell
{
overflow: visible;
}
</style>
<script>
function initMenus(e) {
$(".templateCell").each(function () {
eval($(this).children("script").last().html());
});
}
function onAutoCompleteSelectX(e) {
var dataItem = this.dataItem(e.item.index());
var url = '#Url.Action("GetArticle", "Fiche")';
$.ajax({
url: url,
data: { code: dataItem.Code }, //parameters go here in object literal form
type: 'GET',
datatype: 'json',
success: function (data) {
if (data == null)
document.getElementById('labelx').innerHTML = "null";
else
document.getElementById('labelx').innerHTML = data.Code;
},
error: function () {
document.getElementById('labelx').innerHTML = "error";
}
});
}
function onAutoCompleteX() {
var currentId = $(this).attr('id');
//var currentId = $(this).id;
//document.getElementById('labelx').innerHTML = $(this).className; //$obj.attr('id');
return {
text: document.getElementById(currentId).value
//text: $("#id_of_another_autocomplete").val() works fine when i set static id manually
};
}
</script>
<div class="lines-tab-doc">
#(Html.Kendo().Grid<LineAppelOffre>()
.Name("grid-lines-doc")
// Declare grid column
.Columns(columns =>
{
// Cretae all the columns base on Model
columns.Bound(l => l.Document);
columns.Bound(l => l.LigneOriginale);
columns.Template(l => { }).Title(#Resources.Resource.Article)
.HtmlAttributes(new { #class = "templateCell" })
.ClientTemplate(
Html.Kendo().AutoComplete()
.Name("Article")
.HtmlAttributes(new { id = "#=LigneOriginale#", style = "width:100%;" })
.DataTextField("Code")
.Filter(FilterType.Contains)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetArticles", "Fiche").Data("onAutoCompleteX");
})
.ServerFiltering(true);
})
.Events(e => { e.Select("onAutoCompleteSelectX"); }).ToClientTemplate().ToHtmlString()
);
columns.Bound(l => l.Fournisseur);
columns.Bound(l => l.RefArtFrs);
// Edit and Delete button column
columns.Command(command =>
{
command.Edit();
command.Destroy();
}).Width(200);
})
.Events(ev => ev.DataBound("initMenus"))
// Declare ajax datasource.
// CRUD operation are wired back to ASP MVC Controller/Action e.g. HomeController, GetAll
// Set the model Id
.DataSource(datasoure => datasoure.Ajax()
.Model(model =>
{
//model.Id(l => l.Document);
model.Id(l => l.LigneOriginale);
})
.Read(read => read.Action("LinesAppelOffre_Read", "Achat"))
.Create(create => create.Action("LinesAppelOffre_Add", "Achat"))
.Update(update => update.Action("LinesAppelOffre_Update", "Achat"))
.Destroy(delete => delete.Action("LinesAppelOffre_Delete", "Achat"))
.PageSize(10)
)
// Add tool bar with Create button
.ToolBar(toolbar => toolbar.Create())
// Set grid editable.
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Scrollable(scr=>scr.Height(327))
.Sortable()
.Selectable()
.Navigatable()
.Pageable(pageable =>
{
pageable.Refresh(true);
pageable.PageSizes(true);
pageable.Messages(msg => msg.Empty(null));
})
)
</div>
You can get your AutoComplete id like that:
function onAutoCompleteX(e) {
var currentId = e.sender.element.attr('id');
...
}
But I'm not sure if you have explicity set name as "Article" .Name("Article") you will not always get "Artilcle" as id, even if you set it using .HtmlAttributes property.
If so, just try to use different attribute then id and get is same way.
i used document.activeElement
Browser compatibility
Chrome 2
Firefox (Gecko) 3.0
Internet Explorer 4
Opera 9.6
Safari 4.0

Categories

Resources