Radio Button doesn't reflect Model's value - kendo-ui

I have a kendo Grid for a class, and for that class I've built an editor template to produce a radio button for one of the fields.
This radio button doesn't reflect propertie's value and is always false, although I've checked the value, by printing it on the form, and I'm sure it's true. If I set a default value for that field, the radio button will reflect that value, regardless of the real value of the field.
I should note that I'm using a client template to display a text for that field, and it works fine.
This is the Grid:
#(Html.Kendo().Grid<Class>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(x => x.BActive).ClientTemplate("#= BActive ? 'Open':'Close' #");
/// removed for brevity
})
.Editable(editable => editable.Mode(GridEditMode.PopUp))
.DataSource(ds => ds.Ajax()
.Model(model => {
model.Id(x => x.SWhCode);
model.Field(x => x.BActive).DefaultValue(true);
})
)
)
And this is the lines that produce the radio button inside the editorTemplate:
<label>
#Html.RadioButtonFor(x => x.BActive, true, new { #class = "radio-inline" }) Open
</label>
<label>
#Html.RadioButtonFor(x => x.BActive, false, new { #class = "radio-inline" }) Close
</label>

bool type will be render in client like this
true => True
false => False
Have you try to inspect your element rendered in HTML? You'll see that the bool value transform into capitalize string. To overcome this you should change true and false in radio button with type string too.
Your view code should be like this
<label>
#Html.RadioButtonFor(x => x.BActive, "true", new { #class = "radio-inline" }) Open
</label>
<label>
#Html.RadioButtonFor(x => x.BActive, "false", new { #class = "radio-inline" }) Close
</label>

Related

Unable to get the value of the combo set to the viewmodel

I have implemented the cascading feature of kendo drop down. While trying to save the information, I am not able to get the value of the combo in my viewmodel. If I comment the name attribute, I do get the value however I need the name attribute for the cascading feature to work. I was trying a workaround using jquery to set the model value but getting errors. Could somebody tell me how to fix this issue.
Sales Organisation Combo
<div class="form-group">
#Html.LabelFor(model => model.Company, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-6">
<div class="editor-field">
#(Html.Kendo().ComboBoxFor(model => model.CountryCode)
.Name("SalesOrganisation")
.HtmlAttributes(new { style = "width:100%" })
.DataTextField("CompanyCodeCompany")
.DataValueField("CountryCode")
.Filter("contains")
.MinLength(3)
.DataSource(dataSource => dataSource
.Read(read => read.Action("RequestHeader_SalesOrganisation", "Request").Type(HttpVerbs.Post))
.ServerFiltering(true)
)
)
</div>
#Html.ValidationMessageFor(model => model.Company, "", new { #class = "text-danger" })
</div>
</div>
Sales Office combo
<div class="form-group">
#Html.LabelFor(model => model.SalesOffice, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-6">
<div class="editor-field">
#(Html.Kendo().ComboBoxFor(model => model.SalesOfficeID)
// .Name("SalesOffice")
.HtmlAttributes(new { style = "width:100%" })
.DataTextField("SalesOffice")
.DataValueField("SalesOfficeID")
.AutoBind(false)
.Value("")
.DataSource(dataSource => dataSource
.Read(read =>
{
read.Action("RequestHeader_SalesOffice", "Request")
.Type(HttpVerbs.Post)
.Data("GetFilterOption");
}).ServerFiltering(true)
).CascadeFrom("SalesOrganisation").Filter("contains")
)
</div>
#Html.ValidationMessageFor(model => model.SalesOffice, "", new { #class = "text-danger" })
</div>
</div>
Javascript for cascading feature to work
function GetFilterOption() {
return {
id: $('#SalesOrganisation').val()
}
}
Javascript - Trying to set the model which doesnt work
function GetFilterOption() {
var countryCode = $('#SalesOrganisation').val();
var model = $('#SalesOrganisation').data('kendoComboBox');
model.value = countryCode;
return id = countryCode;
}
When you use .ComboBoxFor(), you should not use .Name().
When you use .ComboBoxFor(m => m.FieldName) then the id/name attribute will be set to "FieldName" by kendo's implementation of the Razor helper and matches the name of your model field.
If you then use .Name("SomeOtherFieldName"), you change the id/name attribute to "SomeOtherFieldName" and it no longer matches the field name of your model, which is why you no longer get the value.
What you want to do is not use .Name() and set up the .CascadeFrom() appropriately, i.e.
#(Html.Kendo().ComboBoxFor(model => model.CountryCode)
....
#(Html.Kendo().ComboBoxFor(model => model.SalesOfficeID)
.CascadeFrom("CountryCode")
function GetFilterOption() {
return {
id: $('#CountryCode').val()
}
}

CheckBox and id value to actionresult in kendo ui with ajax binding

I am developing a MVC with kendo UI grid. In which I have grid and one Button. Grid contains check-box. When We click on button check box value(true/false) and Record id should go to action result.
using (Html.BeginForm("Update", "Model"))
{
Html.Kendo().Grid(Model.Users)
.Name("grid")
.Columns(columns =>
{
columns.Bound(o => o.UserName).Width("300px");
columns.Bound(o => o.IsLicensed).Template(o =>
{%><%: Html.CheckBox("license",o.IsLicensed)%> <%: Html.Hidden("id", o.UserId) %><%}).Width("200px");
})
.Resizable(resize => resize.Columns(true))
.Sortable(sorting => sorting.Enabled(true))
.Filterable(f => f.Enabled(true))
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(new int[] {10, 20, 50, 100})
.ButtonCount(5))
.Render();
%>
<p>
<input class="k-primary k-button" type="submit" value="Save" name="selectedValues"/>
</p>
<%
Html.EndForm();
}
%>
</div>
<% });
And my actionresult looks as below
public ActionResult Update(string[] license, string[] id)
Now here I am using ajax binding and giving datasource. So I can't use Template. We need to use ClientTemplate. ClientTemplate code changes are shown as below.
.Columns(columns =>
{
columns.Bound(o => o.UserName).Width("300px");
columns.Bound(o => o.IsLicensed).Width("300px").ClientTemplate("<input type='checkbox' name='license' ${ IsLicensed == true ? checked='checked' : ''} enabled />" + "<input type='hidden' name='id' value='#= UserId#' />");
})
.DataSource(datasource => datasource.Ajax().Read(read => read.Action("Customers_Read", "UsersLicensing")).PageSize(10))
.Render();
In previous case when Update actionresult is called both parameter are array of 10 as pagesize is 10 and I can update database. But in this case(with ajax and clientTemplate) id parameter is coming as array of 10 items but license parameter depends on number of checkbox selected(if 3 checkbox is selected then license contains 3 element). So I can't make one to one mapping.
Can anybody help me with this or suggest any better idea?
Try this....Worked for me
columns.Template(#<text></text>).
ClientTemplate("<input type='checkbox' class='chkbx' onclick='chkRoleChkBox(this)'
value='#=RoleId#' # if (DefaultRoleflag == 'Y') { # disabled='disabled' # } #/>").Width(30);
You should be able to change your client template as such:
.ClientTemplate("<input type='checkbox' name='license' ${ IsLicensed == true ? checked='checked' : ''} enabled value='#= UserId#' />")
Put the UserId directly into the value of the checkbox. Then when you post, instead of getting an array of "true" you should get an array of the value (which is the UserId) for the checked items.
Update
If you want to be able to get both the checked and unchecked lists, then you can add the hidden field back to the ClientTemplate.
.ClientTemplate(
"<input type='checkbox' name='license' ${ IsLicensed == true ? checked='checked' : ''} enabled value='#= UserId#' />" +
"<input type='hidden' name='id' value='#= UserId#' />"
)
Then when you post you will have an array of all of the IDs in string[] id and an array of the checked IDs in string[] license. Then to get the unchecked, you can use use System.Linq namespace and use Enumerable.Except.
public ActionResult Update(string[] license, string[] id)
{
//....
var unchecked = id.Except(license).ToArray();
//...
}

How to get row value from grid when toolbar is clicked in kendo ui mvc grid

How to get row value from grid when toolbar is clicked in kendo ui mvc grid.
sample View code:
<div id="kendoGrid">
#(Html.Kendo().Grid(Model)
.Name("Grid")
.Columns(columns =>
{
columns.Template(#<input id='chkPayment' type='checkbox' class='check-box' />).Title("Select");
columns.Bound(m => m.PaymentDetailDto.InvoiceNumber);
columns.Bound(m => m.PaymentDetailDto.ModifiedDate).Title("Invoice Date");
})
.ToolBar(x => x.Custom().Text("Make Payment").HtmlAttributes(new { id = "btnMakePayment" }))
)
</div>
Sweeps the grid and search for the value it
$('input[type="checkbox"]').each(function () {
var chkPayment = $(this);
});

How to use Kendo Grid Ajax Read event on demand

I have page with DropDownList and Telerik's Kendo UI Grid Control. When first time page is opened DropDownList has no item selected in it. When user selects value in DropDownList only then Grid should make Ajax call to the server and load corresponding data.
My code works fine when user selects item in DropDownList, but the problem is that first time when page is opened I there is no value in DropDownList and Grid should not make a call to the server.
My question is how can I prevent grid not to make a call to the server if there is no item selected in DropDowList?
<div>
#Html.Kendo().DropDownList().Name("broker").DataTextField("GrandParentName").DataValueField("Id").BindTo(Model).SelectedIndex(#selectedIndex).Events(e => e.Change("brokerChanged"))
</div>
#(Html.Kendo().Grid<OrderViewModel>()
.Name("Orders")
.HtmlAttributes(new {style = "height: 500"})
.Columns(c =>
{
c.Bound(p => p.Id)
.Width(50)
.Title("")
.Sortable(false)
.IncludeInMenu(false)
.ClientTemplate((#Html.ActionLink("Edit", "Index", "Splits", new {Id = "OrderId"}, null).ToHtmlString().Replace("OrderId", "#=Id#")));
c.Bound(p => p.TradeDate)
.Title("Trd Dt")
.Format("{0:d}")
.Width(90)
.HtmlAttributes(new {style = "text-align: right"});
c.Bound(p => p.Price)
.Title("Price")
.Format("{0:n}")
.Width(100)
.HtmlAttributes(new {style = "text-align: right"});
c.Bound(p => p.Status)
.Title("Status");
c.Bound(p => p.Notional)
.Title("Notional")
.Format("{0:n}")
.HtmlAttributes(new {style = "text-align: right"});
})
.Sortable()
.Scrollable()
.ColumnMenu()
.Pageable(x =>
{
x.Enabled(true);
x.PreviousNext(false);
x.PageSizes(false);
x.Info(true);
x.Input(false);
x.Numeric(false);
x.Refresh(true);
x.Messages(y => y.Display("{2} Order(s)"));
})
.Resizable(resize => resize.Columns(true))
.Reorderable(reoder => reoder.Columns(true))
.DataSource(ds => ds.Ajax()
.ServerOperation(false)
.Read(read => read.Action("Action", "MyController").Data("selectedBrokerId")))
)
<script type="text/javascript">
function brokerChanged() {
var grid = $("#Orders").data("kendoGrid");
grid.dataSource.read();
}
function selectedBrokerId() {
var obj = { brokerId: $("#broker").data("kendoDropDownList").value() };
return obj;
}
</script>
Thanks a lot for your time and help.
There is an autobind function for the grid. You can use this to determine whether or not to read when the page first loads. This should work (assuming that selectedIndex determines if a dropdown value is selected):
#(Html.Kendo().Grid<OrderViewModel>()
.Name("Orders")
.HtmlAttributes(new {style = "height: 500"})
.AutoBind(selectedIndex > 0)
//rest of your grid declaration

MVC 3 html.TextBoxFor readonly Properties to be set dynamically

<div class="editor-label" style="position:static">
<%: Html.LabelFor(Model => Model.Date, "Date")%>
<span style="padding-left:52px">
<%: Html.TextBoxFor(Model => Model.Date)%>
Here i want to set the readonly property to the textbox on a button click/Action Click. how do i do it.
At the initial page the data is been displayed as readonly and on the edit button click. This should be changed to editable textbox.I have almost seven textboxes i need to do the same for all.
If I understand your question correctly, this can be accomplished with a little javascript. Here's a simple example.
Render each textbox as readonly on page load:
<%: Html.TextBoxFor(model => model.Date, new { #readonly = "readonly" }) %>
Add a click handler for your edit button that will remove the readonly attribute from each textbox:
$("#editButton").click(function() {
$("#Date").removeAttr("readonly");
});
Use the following:
Html.TextBoxFor(m => m.Whatever, new {id = "", #class="",
placeholder="" #readonly="readonly"})
Hope this helps :)
I think you should put
#readonly = true
or
#readonly = *your-expression-here*

Resources