how to get id from webgrid with javascript - javascript

i try to make webgrid and when i click edit button, the button will pass value from first td in webgrid to my controller, but i cant pass the value.. can some one tell me, what line is error?
this my view
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
firstText: "<< First",
previousText: "< Prev",
nextText: "Next >",
lastText: "Last >>",
mode: WebGridPagerModes.All,
columns: grid.Columns(
grid.Column(header: "Content ID", format: (item) => item.ContentID),
grid.Column(header: "Active", format: (item) => Html.Raw("<input type=\"checkbox\" " + ((item.Active == true) ? "checked='cheked'" : "") + "disabled = 'disabled'/>")),
grid.Column(header: "Image", format: #<img src="#Href("~/images/MobileContent/" + #item.ImageURL)" width="120px" height="50px;" />),
grid.Column("Description"),
grid.Column("Action", format: #<text>
<button class="edit-content">Edit</button>
<button class="remove-content">Remove</button>
</text>)
)
)
}
</div>
</div>
</div>
</div>
</div>
</div>
#section scripts{
<script>
$(".edit-content").click(function () {
var id = $(this).find('td:first').text();
location.href = '/MobileContent/Edit/' + id;
});
$('thead tr th:nth-child(1), tbody tr td:nth-child(1)').hide();
</script>
}
this my controller
public ActionResult Edit(int id)
{
ViewModel.MobileContent.MobileContentViewModel vm = new ViewModel.MobileContent.MobileContentViewModel();
vm.EditContent = EditContent(id);
return View(vm);
}

Have a try
var id = $(this).parent('tr').find('td:first').text();

Try this,
<input type="button" value="Assign" onclick="myfunction(#item.ID);" />
OR
#Html.ActionLink("EditUser", "DYmanicControllerPage", "Test", new { Id = item.ID }, new { #class = "hide" })
function myfunction(obj) {
var id = obj;
location.href = '#Url.Action("DYmanicControllerPage", "Test")?Id=' + id;
}
Controller
public ActionResult DYmanicControllerPage(string Id)
{
var model = new RegisterModel();
int _ID = 0;
int.TryParse(Id, out _ID);
if (_ID > 0)
{
RegisterModel register = GetRegisterUserById(_ID);
model.ID = _ID;
model.Name = register.Name;
model.Address = register.Address;
model.PhoneNo = register.PhoneNo;
}
return View(model);
}

Related

Kendo grid custom filter data is not persisting across result pages, for column with .Filterable(true)

I have a Kendo grid with multiple columns, and only one of the columns has .Filterable(true). When the filter icon above this column is clicked, a custom filter menu pops up. This menu has fields to set the filter data for multiple columns all at once, and then a "Filter" button which sets the datasource filter data to these specifications.
This filtering is working correctly, however the issue is, when going to another page in the results, the column with .Filterable(true) has its filter data removed from the request that is sent to the Controller. All other columns have their filter data persisted across the pages, just not the one with .Filterable(true). This is the case for whichever column is given this attribute.
For example, if I have Column2 set to .Filterable(true), then filter Column2's data and click "Filter", the correct filtered results are populated in the grid. But after clicking to another page of the results, the results reset and no longer filter Column2's data. It also stays like this when clicking back to page 1.
When looking at the DataSourceRequest object passed to the Controller method that gets the grid results, I can see the filter data for this column is there after clicking the "Filter" button. But after clicking to another page in the results, the request object sent to the Controller method no longer has this column included in its filter data.
Any idea why this is happening or how to resolve?
I've included some code for the grid, the custom filter menu function, and the controller method. Please let me know if anything else is needed, thank you.
.cshtml Grid Code
#(Html.Kendo().Grid<Model>()
.Name("MyGrid")
.HtmlAttributes(new { style = "height: 400px;font-size:12px;" })
.Columns(columns =>
{
columns.Bound(m => m.Column1).Title("Column1").Width(90).Filterable(false);
columns.Bound(m => m.Column2).Title("Column2").Width(90).Filterable(true);
columns.Bound(m => m.Column3).Title("Column3").Width(90).Filterable(false);
})
.Sortable()
.AutoBind(false)
.Pageable(p => p
.Refresh(true)
.PageSizes(true)
.ButtonCount(5))
.Scrollable()
.Filterable(f => f
.Mode(GridFilterMode.Menu)
)
.Events(e => e
.FilterMenuInit("OnFilterMenuInit")
)
.Resizable(rs => rs.Columns(true))
.Navigatable()
.Selectable(s => s
.Mode(GridSelectionMode.Single)
.Type(GridSelectionType.Row))
.NoRecords("No Records!")
.DataSource(ds => ds
.Ajax()
.Model(m=> m.Id(p => p.id))
.PageSize(10)
.Read(read => read.Action("GetData", "Test").Data("{arg1: " + 1 + ", arg2:'testarg'}"))
.Update(upd => upd.Action("EditData", "Test"))
.Events(e => e.RequestEnd("onRequestEnd").Error("error_handler"))
.ServerOperation(true))
.js OnFilterMenuInit function:
function OnFilterMenuInit(e) {
e.container
.empty()
.append($('<div class="row"><div class="col-md-2"><span>Column1: </span></div><div class="col-md-1"><input id="col1-operators" /></div><div class="col-md-4"><input id="col1-tb" class="k-textbox" /></div><div class="col-md-1"><input id="col1-logic" /> </div> </div>\
<div class="row"><div class="col-md-2"><span>Column2: </span></div><div class="col-md-1"><input id="col2-operators" /></div><div class="col-md-4"><input id="col2-tb" class="k-textbox" /></div><div class="col-md-1"><input id="col2-logic" /> </div> </div>\
<div class="row"><div class="col-md-2"><span>Column3: </span></div><div class="col-md-1"><input id="col3-operators" /></div><div class="col-md-4"><input id="col3-tb" class="k-textbox" /></div><div class="col-md-1"><input id="col3-logic" /> </div> </div>\
<div class="row"><div class="col-md-4"> <button type="submit" class="k-button k-primary" id="filter">Filter</button> </div><div class="col-md-4"><button type="reset" class="k-button" id="clear">Clear</button></div></div>'));
$('#filter').kendoButton({
click: function () {
var col1 = $('#col1-tb').val();
var col2 = $('#col2-tb').val();
var col3 = $('#col3-tb').val();
var col1Ops = $('#col1-operators').value();
var col2Ops = $('#col2-operators').value();
var col3Ops = $('#col3-operators').value();
var col1Logic = $('#col1-logic').value();
var col2Logic = $('#col2-logic').value();
var col3Logic = $('#col3-logic').value();
var orfilter = { logic: "or", filters: [] };
var andfilter = { logic: "and", filters: [] };
if (col1 != "") {
if (col1Logic == 'and') {
andfilter.filters.push({ field: "Column1", operator: col1Ops, value: col1 })
}
else {
orfilter.filters.push({ field: "Column1", operator: col1Ops, value: col1 })
}
}
if (col2 != "") {
if (col2Logic == 'and') {
andfilter.filters.push({ field: "Column2", operator: col2Ops, value: col2 })
}
else {
orfilter.filters.push({ field: "Column2", operator: col2Ops, value: col2 })
}
}
if (col3 != "") {
if (col3Logic == 'and') {
andfilter.filters.push({ field: "Column3", operator: col3Ops, value: col3 })
}
else {
orfilter.filters.push({ field: "Column3", operator: col3Ops, value: col3 })
}
}
andfilter.filters.push(orfilter);
orfilter = { logic: "or", filters: [] };
e.sender.dataSource.filter(andfilter);
localStorage["kendo-grid-filter"] = kendo.stringify(e.sender.dataSource.filter().filters);
}
});
$('#clear').kendoButton({
click: function () {
e.sender.dataSource.filter({});
localStorage["kendo-grid-filter"] = kendo.stringify({});
}
})
}
.cs TestController GetData Method
public ActionResult GetData([DataSourceRequest]DataSourceRequest request, int? arg1, string arg2, bool arg3 = false, bool arg4 = false)
{
DAL dal = new DAL();
var result = dal.GetDataDAL(request, arg1, arg2, arg3);
return Json(result, JsonRequestBehavior.AllowGet);
}

implementing delete operation in web grid

I am implementing deletion functionality on web grid.
I have a column which has a link delete when it is clicked a JavaScript function is called which sends the id of that record to controller who calls a remove method to delete that record but when i debug the code list of vehicles are returned but when delete link is clicked
it gives a error A data source must be bound before this operation can be performed.
view:
#model IEnumerable<ParkOnMyDrive.Models.Vehicle>
#{
ViewBag.Title = "ViewVehicle"
}
<h2>ViewVehicle</h2>
#{
var grid = new WebGrid(source: Model,
defaultSort: "make",
rowsPerPage: 3);
}
<h2>Vehicle List</h2>
<div id="grid">
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("vehicleType","Type"),
grid.Column("make", " Make"),
grid.Column("modelType", "Model"),
grid.Column("color", "Color"),
grid.Column("registartion", "Registartion"),
grid.Column(
header: "Action",
format: #<text>
<a href="#" id="Delete_#item.vehicleId" >Delete</a></text>)
)
)
Controller:
[HttpPost]
public ActionResult DeleteVehicle(string vehcKey)
{
//string key = "eb306a32-1be0-47ad-a0e8-756af97643b8";
Vehicle vehicleModel = new Vehicle();
string userName = "wasfa_anjum#yahoo.com";
if (ModelState.IsValid)
{
bool success = vehicleModel.RemoveVehicle(vehcKey,userName);
if (success)
{
ModelState.AddModelError("", "Vehicle deleted successfully");
}
else
{
ModelState.AddModelError("", "Vehicle not deleted");
}
}
else
{
}
return View();
}
Model
public bool RemoveVehicle(string vehicleKey,string userName)
{
bool success = false;
using (var session = MvcApplication.Store.OpenSession())
{
var removeVehicle = from vehc in session.Query<Vehicle>()
where vehc.vehicleId == vehicleId
where vehc.userId == userName
select vehc;
if (removeVehicle.Count() > 0)
{
var myVehicle = removeVehicle.FirstOrDefault();
Session.Delete(myVehicle);
Session.SaveChanges();
success = true;
}
}

mvc3 razor - url.action javascript error onClick event

I am having a problem with my url.action and my javascript onClick event call. What I am trying to do is pass my controller and actionresult method as a parameter for my javascript but I keep getting an error of:
Microsoft JScript runtime error: Syntax error, unrecognized expression: /UserManager/filterGrid
for this code:
<div class="webgrid-filter">
<input name="User logged in" type="checkbox" onclick="filterGrid('#Url.Action("filterGrid", "UserManager")')" id="chkboxGridFilter" />
</div>
view
#model IEnumerable<UserManager.Models.vw_UserManager_Model>
#*#model UserManager.Models.vw_UserManager_Model
*#
#{
ViewBag.Title = "User Manager Dashboard";
}
#Html.ActionLink("Create New User", "CreateUser")
<div class="webgrid-filter">
<input name="User logged in" type="checkbox" onclick="filterGrid('#Url.Action("filterGrid", "UserManager")')" id="chkboxGridFilter" />
</div>
<div class="webgrid-wrapper">
#{
ViewBag.Title = "Jobs";
WebGrid grid = new WebGrid(Model, canPage: true, canSort: true, rowsPerPage: 15, selectionFieldName: "selectedRow", fieldNamePrefix: "gridItem");
}
#grid.GetHtml(
fillEmptyRows: true,
tableStyle: "webgrid",
alternatingRowStyle: "webgrid-alternating-row",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
mode: WebGridPagerModes.All,
columns: new[] {
grid.Column("UserName"),
grid.Column("salutation"),
grid.Column("FirstName"),
grid.Column("LastName"),
grid.Column("Password"),
//grid.Column("isactive"),
//grid.Column(header: "Is logged in?", format: (model) => #Html.Raw("<input type='checkbox' checked='" + ((model.isactive) ? "checked" : "unchecked") + "' />")),
grid.Column(header: "User logged in", format: #<text><input name="User logged in"
type="checkbox" #(item.isactive == true ? "Checked" : null) onclick="logUserOff('#Url.Action("LogUserOff", "UserManager", new {userid = item.userid} )')" id="chkboxIsActive" /></text>),
grid.Column("isApproved"),
grid.Column("MaxConcurrentUsers"),
grid.Column("email"),
grid.Column("group_name"),
grid.Column("module_name"),
grid.Column(header:"Edit", format:#<text><div id="btnEditSelectedRow">
"#Html.ActionLink("Edit record", "EditUser", "UserManager", new {
userid = item.userid,
salutation = item.salutation,
firstname = item.FirstName,
lastname = item.LastName,
password = item.Password,
isactive = item.isactive,
isapproved = item.IsApproved,
maxconcurrentusers = item.MaxConcurrentUsers,
email = item.email,
module = item.module_name,
group = item.group_name }, null)</div></text>),
grid.Column(header:"Delete", format:#<text><div id="btnDelSelectedRow">
"#Html.ActionLink("Delete record", "DeleteUser", "UserManager", new {
userid = item.userid,
username = item.UserName,
salutation = item.salutation,
firstname = item.FirstName,
lastname = item.LastName,
password = item.Password,
isactive = item.isactive,
email = item.email,
module = item.module_name,
group = item.group_name }, null)</div></text>)
})
</div><br />
<script type="text/javascript">
$(document).ready(function () {
// Disable checkboxs where a user is not active.
$(".webgrid-wrapper input:not(:checked)").attr("disabled", "disabled");
// Style tables.
function jQueryUIStyling() {
$('input:button, input:submit').button();
$('.webgrid-wrapper').addClass('ui-grid ui-widget ui-widget-content ui-corner-all');
$('.webgrid-title').addClass('ui-grid-header ui-widget-header ui-corner-top');
jQueryTableStyling();
} // end of jQueryUIStyling
function jQueryTableStyling() {
$('.webgrid').addClass('ui-grid-content ui-widget-content');
$('.webgrid-header').addClass('ui-state-default');
$('.webgrid-footer').addClass('ui-grid-footer ui-widget-header ui-corner-bottom ui-helper-clearfix');
} // end of jQueryTableStyling
});
</script>
<script type="text/javascript">
function logUserOff(url) {
var answer = confirm('Are you sure you want to save this data?')
if (answer) {
// alert(url + ": " + value);
$.ajax({
url: url,
type: "POST"
// data: value
}).done(function () {
$(this).addClass("done");
});
return true;
}
else {
return false;
}
};
</script>
<script type="text/javascript">
function filterGrid(url) {
alert($(url).val());
}
</script>
This is the javascript:
<script type="text/javascript">
function filterGrid(url) {
alert($(url).val());
}
</script>
Error originates from jquery-1.5.1:
throw"Syntax error, unrecognized expression: "+a
Anyone know what I am doing wrong? Thanks!
this error id caused the way you are showing the value of your URL in the alert.
You should write it like this
function filterGrid(url) {
alert(url);
}

Partial View not working propely in index view.

I am developing MVC application and using razor syntax.
In this application I am giving comment facility.
I have added a partial view, which loads the comment/Records from DB.
In below image, we can see the comment box which is called run-time for employee index view.
Now as we can see comment box, I called at run-time, which is partial view, but problem is I can add comment for only on first record...after first record that button wont work at all...
anything is missing ?
Is there separate process when we call any partial view run-time and make in action on it ?
See the pic...
Here is the code....
#model PagedList.IPagedList<CRMEntities.Customer>
<link href="../../Content/Paging.css" rel="stylesheet" type="text/css" />
<link href="../../Content/EventEntity.css" rel="stylesheet" type="text/css" />
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")%>" type="text/javascript"></script>
<div id="ListBox">
<div id="ListHeader">
All customers(#Model.TotalItemCount)
</div>
#foreach (var item in Model)
{
<div id="ListContent">
<span class="ContentTitleField">#Html.ActionLink(item.Name, "Details", new { id = item.Id }, new { #style="color:#1A6690;" })</span>
#if (item.Owner != null)
{
<span class="ContentSecondaryField">#Html.ActionLink(item.Owner.FullName, "Details", "Employee", new { id = item.OwnerId }, new { #style = "color:#1A6690;" })</span>
}
<span class="ContentSecondaryField">#Html.DisplayFor(modelItem => item.Address)</span>
<span id="flagMenus">
#Html.Action("ShowFlag", "Flagging", new { entityId=item.Id, entityType="Customer"})
</span>
#if (item.Opportunities.Count > 0)
{
<span class="FlagOpportunity">#Html.ActionLink("opportunities(" + item.Opportunities.Count + ")", "Index", "Opportunity", new { custid = item.Id }, new { #style = "color:#fff;" })</span>
}
<div style="float:right;">
#Html.Action("SetRate", "Rating", new { entityId = item.Id, rating = item.Rating, entityname = "Customer" })
</div>
<div id="subscribeStatus" style="float:right;">
#Html.Action("ShowSubscribedStatus", "Subscribing", new { entityId = item.Id, entityType = "Customer" })
</div>
<div class="ListLinks">
<span class="ListEditLinks">
<span style="float:left;">#Html.ActionLink("edit", "Edit", new { id = item.Id })</span>
<span class="LinkSeparator"></span>
</span>
<span class="ListAddLinks">
<span style="float:left;">#Html.ActionLink("+opportunity", "Create", "Opportunity", new { custid = item.Id }, null)</span>
<span class="LinkSeparator"></span>
<span>#Ajax.ActionLink("+Comment", null, null, null, new { id = item.Id, #class = "addremark" })</span>
</span>
<div class="RemarkBox"></div>
</div>
<span class="CommentAdd">
</span>
<div class="CommentBlock">
</div>
<span>#Ajax.ActionLink("Add Comment", null, null, null, new { id = item.Id, #class = "addremark" })</span>
</div>
}
<div class="PagingBox">
#Html.Action("CreateLinks", "Pager", new { hasPreviousPage = Model.HasPreviousPage, hasNextPage = Model.HasNextPage, pageNumber = Model.PageNumber, pageCount = Model.PageCount })
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('.RemarkBox').hide();
$('a.addremark').click(function () {
var url="#Html.Raw(Url.Action("ShowCommentBox", "Comment", new { Id = "idValue", EntityType = "Customer" }))";
url=url.replace("idValue",event.target.id);
$('.RemarkBox').load(url);
$(this).closest('div').find('div.RemarkBox').slideToggle(300);
return false;
});
$("a.pagenumber").click(function () {
var page = 0;
page = parseInt($(this).attr("id"));
$.ajax({
url: '#Url.Action("GetPagedCustomers")',
data: { "page": page },
success: function (data) { $("#customerlist").html(data); }
});
return false;
});
});
</script>
To expand on what Alberto León is saying, the partial page load will not cause the document ready event to fire, so the re-rendered elements will not have the javascript event handlers registered after the first comment is added.
To resolve this, you could put the event registration code into a function, and call this both from the document ready event and the success handler of the AJAX call. Something like this:
function AssignEventHandlers() {
$('a.addremark').click(function () {
....
});
$("a.pagenumber").click(function () {
var page = 0;
page = parseInt($(this).attr("id"));
$.ajax({
url: '#Url.Action("GetPagedCustomers")',
data: { "page": page },
success: function (data) {
$("#customerlist").html(data);
AssignEventHandlers();
}
});
return false;
});
}
$(document).ready(function () {
$('.RemarkBox').hide();
AssignEventHandlers();
}
In success function you need to recall the javascript, or the jquery code that makes the button work. Is an error that taked me a lot of time. Anything uploaded by ajax or any renderpartiAl needs to recall javascript.
$('.RemarkBox').load(url, function() {
//RECALL JAVASCRIPT
});

How to get the row ID from a Kendo Grid with a double click

I'm currently testing the Kendo UI MVC Extensions Beta.
I'm trying to implement a double click - edit but I don't know how I can get the rowId.
JavaScript:
$('#GridPedidos table tr').live('dblclick', function () {
alert(' grid dbl clicked');
});
View:
#(Html.Kendo().Grid(Model) _
.Name("GridPedidos") _
.Columns(Sub(column)
column.Bound(Function(item) item.idPedidoDocumentacao).Width("5%")
column.Bound(Function(item) item.descEstadoPedidoDoc).Width("25%")
column.Bound(Function(item) item.descTipoPedidoDoc).Width("25%")
column.Bound(Function(item) item.data).Width("25%").Format("{0:dd-MM-yyyy}")
column.Command(Function(item) item.Destroy()).Width("10%")
End Sub) _
.DataSource(Sub(ds)
ds.Ajax().ServerOperation(False).Read(Sub(s)
s.Action("GetListaGrid", "listaPedidos")
End Sub).Create(Sub(s)
s.Action("detalhePedido", "Pedidos")
End Sub).Model(Sub(m)
m.Id(Function(p) p.idPedidoDocumentacao)
End Sub).Destroy(Sub(d)
d.Action("apagaPedido", "listaPedidos")
End Sub)
End Sub) _
.Selectable()
)
I can detect the double click with this function, but how do I get the id?
I've done this example with client side api and an equivalent with the MVC extensions.
Create a grid div, to create a grid at run time.
<div id="grid" style="width: 400px;"></div>
Created a row template so that I could give the element an id tag.
<script id="rowTemplate" type="text/x-kendo-tmpl">
<tr>
<td id="EmployeeId">
${ EmployeeID }
</td>
<td>
${ FirstName }
</td>
<td>
${ LastName }
</td>
</tr>
</script>
Initialize the grid and bind data.
<script>
$(document).ready(function () {
$("#grid").kendoGrid({
columns: [
"EmployeeID"
,{
field: "FirstName",
title: "First Name"
},{
field: "LastName",
title: "Last Name"
}
],
dataSource: {
data: [
{
EmployeeID: 0,
FirstName: "Joe",
LastName: "Smith"
}, {
EmployeeID: 1,
FirstName: "Jane",
LastName: "Smith"
}
],
schema: {
model: {
id: "EmployeeID",
fields: {
EmployeeID: {type: "number" },
FirstName: { type: "string" },
LastName: { type: "string" }
}
}
},
pageSize: 10
},
scrollable: {
virtual: true
},
sortable: true,
pageable: true,
rowTemplate: kendo.template($("#rowTemplate").html())
});
//Add a double click event that will return the text in the EmployeeId column.
$('#grid table tr').dblclick(function () {
alert($(this).find("td[id=EmployeeId]")[0].innerText);
});
});
</script>
--EDIT--
I've also gone ahead and created an MVC extensions example, the approach is the same via the template route.
Model class:
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
}
View code:
<script type="text/javascript">
function OnDataBound() {
$('#OtherGrid table tr').dblclick(function () {
alert($(this).find("span[id=EmployeeId]")[0].innerText);
});
}
</script>
#(Html.Kendo().Grid<Employee>()
.Name("OtherGrid")
.Columns(columns =>
{
columns.Bound(p => p.EmployeeId).ClientTemplate("<span id=\"EmployeeId\">#: EmployeeId #</span>");
columns.Bound(p => p.Name);
})
.DataSource(dataSource => dataSource
.Ajax() // Specify that the data source is of ajax type
.Read(read => read.Action("GetEmployees", "Home")) // Specify the action method and controller name
)
.Events(e => e.DataBound("OnDataBound"))
)
Controller:
public ActionResult GetEmployees([DataSourceRequest]DataSourceRequest request)
{
List<Employee> list = new List<Employee>();
Employee employee = new Employee() { EmployeeId = 1, Name = "John Smith" };
list.Add(employee);
employee = new Employee() { EmployeeId = 2, Name = "Ted Teller" };
list.Add(employee);
return Json(list.ToDataSourceResult(request));
}
Hope this helps!
I achieved what i was looking for with this js
$('#GridPedidos table tr').live('dblclick', function () {
var grid = $("#GridPedidos").data("kendoGrid");
var dItem = grid.dataItem($(this));
if (dItem != null) {
detalhePedido(dItem.id);
}
});
To open edit mode with double click you need to register the double click event with the grid like this:
var grid = $("#grid").data("kendoGrid");
grid.element.delegate("tbody>tr", "dblclick", function () {
grid.editRow($(this));
});

Categories