I am trying to add Custom Button to each row of Kendo Grid, but I am not getting the desired output.So my requirement is to add dynamic buttons to each row and on clicking on these button I need to process few thing for which I need few column values to be passed to that button click.
I have tried something like
#(Html.Kendo().Grid(Model)
.Name("Grid")
.Columns(columns =>
{
columns.Bound(o => o.Id);
columns.Bound(o => o.TBRId).Width(100).Title(UI_Resources.ListLabel_TBRId);
columns.Bound(o => o.THUQuantity).Width(50).Title(UI_Resources.ListLabel_THUQuantity).HtmlAttributes(new { style = "text-align:right" });
columns.Bound(o => o.Id).ClientTemplate("<input width='50px' type='button' value= " + UI_Resources.Button_Details + " onclick='onDetailUnitClick(#= Id #);' class='btn btnTable' />").Width(50).Title("");
columns.Bound(o => o.IsPOD).ClientTemplate("#= AppendZeroPODButton(Id,IsPOD) #").Width(60).Title("");
})
.Pageable()
.Sortable()
.Scrollable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("GetUnitsForShipment", "POD",new { shipmentId = #Model, Mode = "POD" }))
)
)
/*JavaScript */
function onDetailUnitClick(Id) {
var podDateTime = $("#enteredPODDateTime").val();
var stopId = $("#hiddenStopId").val();
var mode = '';
if (typeof $("#hiddenMode").val() != 'undefined')
mode = $("#hiddenMode").val();
window.location.href = "/POD/Details/" + Id + "?stopId=" + stopId + "&date=" + podDateTime + "&mode=" + mode;
};
function AppendZeroPODButton(Id, isPOD) {
if (isPOD == true) {
return "<input width='100px' type='button' value= 'Zero POD' onclick='onPODUnitClick(" + Id + ",1);' class='btn btnTable btn-success' disabled />";
}
else {
return "<input width='100px' type='button' value= 'Zero POD' onclick='onPODUnitClick(" + Id + ",1);' class='btn btnTable btn-danger' />";
}}
Can you please suggest me what I am doing wrong!!
It was working for Telerek MVC grids.
Thanks
Yogendra Singh
It worked if I change the ClientTemplate to
columns.Template(t => t.IsPOD).HeaderTemplate("").ClientTemplate(#"<a href='javascript: void(0)' class='btn btnTable' onclick='onDetailUnitClick(#= Id #)' title='button delete'>" + UI_Resources.Button_Details + " </a>").Title("").Width(50);
AND
columns.Bound(p => p.IsPOD).ClientTemplate("# if( IsPOD == true) { # <a href='javascript: void(0)' class='btn btnTable btn-success' onclick='onPODUnitClick(#= Id #, 1)' title='Zero POD'>" + UI_Resources.Button_ZeroPOD + "</a> # } else {# <a href='javascript: void(0)' class='btn btnTable btn-danger' onclick='onPODUnitClick(#= Id #, 1)' title='Zero POD'>" + UI_Resources.Button_ZeroPOD + "</a> # } #").Title("").Width(100);
You can add Custom button as well.Refer this http://demos.kendoui.com/web/grid/custom-command.html
Related
I'm so tired to resolve this problem. I just want to display two values, For example in columns.Foreignkey. Showing Name and Id on the same columns. How do I do this?
#(Html.Kendo().Grid<Project_Test.Models.Workcenter>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.WorkcenterCode)
.Width(80)
.Title("Workcentercode")
.ClientTemplate("");
columns.Bound(p => p.WorkCenterSection)
.Width(84)
.Title("WorkcenterSection");
columns.ForeignKey(p => p.WorkcenterCategory,
(System.Collections.IEnumerable)ViewBag.WorkcenterCategory,
"WorkcenterCategoryID",
"WorkcenterCategoryName")
.Title("Category")
.Width(200);
//command.Custom("Details").Click("showDetails").HtmlAttributes(new { #class = "k-font-icon k-i-insert-unordered-list " });
command.Custom(" ")
.Click("showDetails")
.HtmlAttributes(new { #class = "btn btn-default btn-xs glyphicon glyphicon-list-alt" })
.Width(230);
})
//.Events(e => e.DataBound("onDataBound"))
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable
.Mode(GridEditMode.PopUp)
.TemplateName("Workcent")
.DisplayDeleteConfirmation("Are you sure to delete this Workcenter")
)
.Sortable()
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.Messages(messages => messages.Refresh("Click to refresh"))
.ButtonCount(8)
)
.Groupable()
.Resizable(resize => resize.Columns(true))
.Reorderable(reorder => reorder.Columns(true))
.Selectable()
.Scrollable()
.HtmlAttributes(new { style = "height:580px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Events(events => events.Error("error_handler"))
.Model(model =>
{
model.Id(p => p.WorkcenterID);
model.Field(p => p.WorkcenterID).Editable(true);
model.Field(p => p.UpdatedBy).DefaultValue(User.Identity.Name);
model.Field(p => p.CreatedBy).DefaultValue(User.Identity.Name);
})
.Create(update => update.Action("Employee_Create", "Home"))
.Read(read => read.Action("List", "Home"))
.Update(update => update.Action("Products_Update", "Home"))
.Destroy(update => update.Action("adress_Destroy", "Home"))
)
)
The ForeignKey column is just displaying the WorkcenterCategoryName associated with the corresponding WorkcenterCategoryID from the bound list(ViewBag.WorkcenterCategory).
Just make the WorkcenterCategoryName of each element in ViewBag.WorkcenterCategory contain the text you actually want to display, i.e.
"IDOfSelectedItem (TextOfSelectedItem)"
instead of just
"TextOfSelectedItem"
Edit to be more specific:
I'm assuming your server action is filling ViewBag.WorkcenterCategory something like:
ViewBag.WorkcenterCategory = GetWorkcenterCategories()
.Select(x => new
{
WorkcenterID = x.ID,
WorkcenterName = x.Name
});
Let's say this returns the list:
{ WorkcenterID = 1, WorkcenterName = "One" },
{ WorkcenterID = 2, WorkcenterName = "Two" }
Then the ForeignKey column maps a particular key to the corresponding item in the list bound to it (ViewBag.WorkcenterCategory) and the text value associated to the key will be displayed, whatever is contained in the WorkcenterName field.
i.e. value of 1 will display "One" in the grid.
If you want to display more than just the name of the Workcenter, then set the WorkcenterName of the objects in the ViewBag.WorkcenterCategory list to the text you want to have displayed, i.e.:
ViewBag.WorkcenterCategory = GetWorkcenterCategories()
.Select(x => new
{
WorkcenterID = x.ID,
WorkcenterName = x.ID + " (" + x.Name + ")"
});
This would return the list:
{ WorkcenterID = 1, WorkcenterName = "1 (One)" },
{ WorkcenterID = 2, WorkcenterName = "2 (Two)" }
And a value of 1 would now display "1 (One)" instead of just "One".
I'm new to ASP.NET MVC using Kendo-UI and trying to load data from entity to Grid. is there a way to concatenate two fields in a column?
#(Html.Kendo().Grid(Model)
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.employeeId).Title("ID");
columns.Bound(p => p.firstname +" "+p.lastname).Title("Name");
})
.Pageable()
.Sortable()
.Scrollable(scr=>scr.Height(430))
.Filterable()
.DataSource(datasource => datasource
.Ajax()
.PageSize(20)
.ServerOperation(false)
)
I tried this solution but I get an error.
{"Bound columns require a field or property access expression."}
You can make use of the row template function to achieve it. Please find the snippet below and full demo can be seen here.
#(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.EmployeeViewModel>()
.Name("grid")
.HtmlAttributes(new { style = "width: 750px;height:430px;" })
.Columns(columns =>
{
columns.Template(e => { }).ClientTemplate(" ").Width(140).Title("Picture");
columns.Bound(e => e.Title).Width(400).Title("Details");
columns.Bound(e=> e.EmployeeID).Title("ID");
})
.ClientRowTemplate(
"<tr data-uid='#: uid #'>" +
"<td class='photo'>" +
"<img src='" + Url.Content("~/Content/web/Employees/") +"#:data.EmployeeID#.jpg' alt='#: data.EmployeeID #' />" +
"</td>" +
"<td class='details'>" +
"<span class='title'>#: Title #</span>" +
"<span class='description'>Name : #: FirstName# #: LastName#</span>" +
"<span class='description'>Country : #: Country# </span>" +
"</td>" +
"<td class='employeeID'>" +
"#: EmployeeID #" +
"</td>" +
"</tr>"
)
.Scrollable()
)
One of the ways you can achieve what you are trying to do is by creating a Name property in your Model with just a getter which concatenates firstname and lastname, like this
public string Name { get { return string.Format("{0} {1}", firstname, lastname); } }
Then you can bind the Name to the grid, like this
columns.Bound(p => p.Name);
You should be good to go...
I am working with ASP.NET MVC 4 with Kendo UI(kendo grid).Below is sample code of Kendo Grid -
#(Html.Kendo().Grid(Model.Users).Name("Grid").Columns(columns =>
{
columns.Bound(p => p.FirstName);
columns.Bound(p => p.LastName);
columns.Bound(p => p.UserName);
columns.Bound(p => p.Email);
columns.Bound(o => o.IsActive).ClientTemplate(links).Title("Action");
})
In the above code my IsActive column have some links for Actions like Edit,Update,Delete.And i am adding those links into Kendo grid by links variable.And I want to use links variable on the basis of conditions.Means i want conditional ClientTemplate here.
So anyone suggest how can make a conditional ClientTemplate in kendoGrid ?
2) Also i want to add condition on the basis on the bool field value of my model(Model.Users).
So i want to know how we can get that field from Model.Users model in kendo grid for each row.Like -
.ClientTemplate(if(IsAdmin && ViewBag.IsActive){.....} else{....})
You can try like below code..may be this help you..
columns.Bound(p => p.Active).ClientTemplate("\\#if('#=Active#'=='Y') {\\<input type='button' value='OK' />\\}\\#");
or may be use
"#= (Active) ? ' ' : 'your code here' #"
You can use the following piece of code:
#(Html.Kendo().Grid(Model.Users).Name("Grid").Columns(columns =>
{
columns.Bound(p => p.FirstName);
columns.Bound(p => p.LastName);
columns.Bound(p => p.UserName);
columns.Bound(p => p.Email);
columns.Bound(o => o.IsActive).ClientTemplate("#if(IsActive){#<a href='javascript:void(0)' >Edit</a>#}#").Title("Action");
})
I'm concatenating a name and using a javascript function which made condition testing much easier, plus you can get access to multiple fields:
cshtml:
#(Html.Kendo().Grid<Debtors>()
.Name("Debtors")
.Columns(columns =>
{
columns.Bound(c => c).Title("Name").ClientTemplate("#=showName(data)#");
columns.Bound(c => c.Busname);
...
})
...
)
js:
function showName(data) {
var returnName = "";
if (data.Lname) {
returnName = data.Lname;
if (data.Fname) {
returnName += ", " + data.Fname;
if (data.Mi) {
returnName += " " + data.Mi;
}
}
}
return returnName;
}
Can anybody help me in implementing Drupal 7 'Keep me logged in' feature and customize the error messages in login form.
In page--front.tpl.php i used <?php print front_login();?> for the login form and front_login() function is in template.php.
template.php functions are
<?php
function front_login() {
global $user;
if ($user->uid == 0) {
$form = drupal_get_form('front_login_form');
return theme('status_messages').render($form);
} else {
return '<div id="loginbar">' . t('Welcome back ') . ucwords($user->name) . '</div>';
}
}
function front_login_form($form, &$form_state) {
global $base_url;
$form['#id'] = 'login';
$haveAccount = '<div class="title"><span>Already have an account?</span><br>Log In Here</div>';
$forgot = '<div class="forgot">Forgot your password?</div>';
$form['#validate'] = user_login_default_validators();
$form['#submit'][] = 'front_login_form_submit';
$form['name'] = array(
'#type' => 'textfield',
'#id' => 'user_login',
'#prefix' => $haveAccount . '<div class="inputholder"><div class="icon glyphicon glyphicon-user"></div>',
'#suffix' => '</div>',
'#required' => TRUE,
'#attributes' => array('class' => array('footerinput'), 'placeholder' => array(t('Username'))),
);
$form['pass'] = array(
'#type' => 'password',
'#id' => 'pwd_login',
'#prefix' => '<div class="inputholder"><div class="icon"><img src="' . $base_url . '/' . drupal_get_path('theme', 'foodnet') . '/images/icon-2.png"></div>',
'#suffix' => "</div>",
'#required' => TRUE,
'#attributes' => array('class' => array('footerinput'), 'placeholder' => array(t('Password'))),
);
$form['keep_logged'] = array(
'#type' => 'checkbox',
'#title' => t('Keep me logged in'),
'#default_value' => 1,
'#prefix' => '<div class="row">
<div class="col-md-6">
<div class="checkbox"><label>',
'#suffix' => '</label></div>
</div>'
);
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
'#type' => 'submit',
'#id' => 'but_login',
'#name' => 'but_login',
'#value' => t('Log In ยป'),
'#prefix' => '<div class="col-md-6"><div class="loginBtn">',
'#suffix' => '</div></div> </div>' . $forgot
);
$form['actions']['submit']['#attributes']['class'][] = 'btn';
$form['actions']['submit']['#attributes']['class'][] = 'btn-yellow';
$form['actions']['submit']['#attributes']['class'][] = 'btn-lg';
$form['actions']['submit']['#attributes']['class'][] = 'col-md-12';
return $form;
}
function front_login_form_submit($form, &$form_state) {
global $user;
$user = user_load($form_state['uid']);
$form_state['redirect'] = 'profile';
user_login_finalize($form_state);
if($form_state['values']['keep_logged'] ==0){
ini_set('session.cookie_lifetime', 0);
foreach ($_COOKIE as $key => $value) {
setcookie($key, $value, 0);
}
setcookie('_fnet_keepLogged', 0, time()+200000);
}else{
ini_set('session.cookie_lifetime', 2000000);
setcookie('_fnet_keepLogged', 1, time()+200000);
}
}
The login functionality works fine but I cannot customize the error messages. I have to set the errors inside the form. Please help.
When user click the 'Keep me logged in' checkbox I set '_fnet_keepLogged' cookie to 1, else to 0. I know that the default expiration of cookie in drupal is 23 days. I need to change that according to the value of '_fnet_keepLogged' cookie. Please help for this.
Thanks in advance.
I have a kendo UI grid in my page. Below is the code of kendo UI grid with CRUD datasource actions.
#(Html.Kendo().Grid<Gts.GlaspacLX.Web.ViewModel.ProductViewModel>()
.Name("xyzGrid")
.Columns(columns =>
{
columns.Bound(p => p.SelectedProductCategory).EditorTemplateName("_ProductDropDownList").Title("Product Category").HtmlAttributes(new { #tabindex = "8" });
columns.Bound(p => p.Name).Width(130).Title("% Off").HtmlAttributes(new { #tabindex ="9" });
columns.Bound(p => p.Rate).Width(130).HtmlAttributes(new { #class = "prodDiscRtAlign",#tabindex= "10" });
columns.Bound(p => p.Hours).Width(130).HtmlAttributes(new { #class = "prodDiscRtAlign",#tabindex= "11" });
if (SiteContext.CurrentUser.HasPrivilege(PrivilegeNames.Maintenance, PermissionNames.DELETE))
{
columns.Command(command => { command.Destroy(); }).Width(110).Title("Delete").HtmlAttributes(new { #tabindex = "12" });
}
})
.ToolBar(commands =>
{
commands.Create();
commands.Save();
})
.Editable(editable => editable.Mode(GridEditMode.InCell).CreateAt(GridInsertRowPosition.Bottom))
.Sortable()
.Navigatable()
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
.Model(model =>
{
model.Id(p => p.ProductID);
model.Field(p => p.SelectedProductCategory).DefaultValue(ViewBag.DefaultProductCategory);
})
.Read(read => read.Action("Product_Read", "ProductController"))
.Update(update => update.Action("Product_Update", " ProductController "))
.Create(create => create.Action("Product_Create", " ProductController "))
.Destroy(update => update.Action("Product_Destroy", " ProductController ")
))
.Events(e => e.Edit("proField").DataBound("boundProductChange"))
)
Below is the screen shot of "Save" button just after the kendo grid. It's responsible for any create/update operation of the page.
My problem is once I clicked on Save button for any create or update operation its posting the action method twice. You can see the console of above screen shot.
Below is the piece of the code of my controller's action method:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Product_Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<ProductViewModel> product){
return Json(results.ToDataSourceResult(request, ModelState));
}
Below is proField function code :-
function proField(e) {
var defaultproduct = $("#DefaultProductCategory").val();
defaultproduct = "\n" + defaultproduct + "select ";
if (e.model.SelectedProductCategory == "Default" && (e.sender._editContainer[0].textContent == defaultproduct || e.sender._editContainer[0].textContent == "\n select ")) {
e.sender._editContainer[0].disabled = true;
e.sender._editContainer[0].children[0].textContent = "Default";
e.sender.table[0].rows[1].cells[1].click();
e.sender.table[0].rows[1].cells[4].disabled = true;
}
}
after insert any record you should return primary(Id) key to view.
see kendo demo.