Telerik MVC Grid with multiple checkboxes in a single row, single column - asp.net-mvc-3

I am trying to construct a Telerik MVC grid and am having great difficulty constructing a row which contains more than one checkbox in a grid cell.
So far my attempt has gotten me only half way there. It displays a single row with a whole bunch of check boxes in the first cell, but when I want to add a record via the "Insert" toolbar button, I get a blank line.
Here is my model and view. Any help would be appreciated.
public class MyModel {
public MappingsModel[] Mappings { get; set; }
public class MappingsModel {
public CustomerRoleModel[] CustomerRoles { get; set; }
public int[] SelectedCustomerRoleIds { get; set; }
}
public class CustomerRoleModel {
public int Id { get; set; }
public string Name { get; set; }
public bool Selected { get; set; }
}
}
#(Html.Telerik().Grid(Model.Mappings)
.Name("rules-grid")
.DataKeys(keys =>
{
keys.Add(x => x.Id);
})
.DataBinding(dataBinding =>{
dataBinding.Ajax()
.Select("RuleList", "MyController")
.Insert("RuleInsert", "MyController")
.Update("RuleUpdate", "MyController")
.Delete("RuleDelete", "MyController");
})
.Columns(columns =>
{
columns.Bound(x => x.CustomerRoles)
.Template(#<text>
#foreach (var role in #item.CustomerRoles) {
<text><input type="checkbox" value="#(role.Id)" id="role_#(role.Id)" name="SelectedCustomerRoleIds" disabled="disabled" </text>
if(role.Selected) {
<text>checked="checked"</text>
}
<text>/><label for="role_(#role.Id)">#role.Name</label><br /></text>
}
</text>
)
.Width(500);
columns.Command(commands =>
{
commands.Edit();
commands.Delete();
})
.Width(180);
})
.ToolBar(commands => commands.Insert())
.EnableCustomBinding(true));
Update
I have tried the suggestion offered by #howcheng but this renders the checkboxes like so:
[object Object],[object Object],[object Object],[object Object]
The data I'm getting back via Ajax looks valid even though it doesn't looked correct below. Any ideas?
data: [{Name:null, Age:0,…}]
0: {Name:null, Age:0,…}
Age: 0
CustomerRoles: [{Name:Administrators, Selected:false, Id:1}, {Name:Forum Moderators, Selected:false, Id:2},…]
0: {Name:Administrators, Selected:false, Id:1}
1: {Name:Forum Moderators, Selected:false, Id:2}
2: {Name:Guests, Selected:false, Id:4}
3: {Name:Registered, Selected:false, Id:3}
Id: 1
Name: null
total: 1

What you've done is define a display template. In order to edit, you need a custom editor template. Create a partial view in your /Views/Shared/EditorTemplates directory and call it something like "CustomerRoles.cshtml".
Editor template:
#model CustomerRoleModel[]
#foreach (CustomerRoleModel crm in Model)
{
// checkbox code goes here
}
Grid code:
#(Html.Telerik().Grid(Model.Mappings)
.Columns(columns =>
{
columns.Bound(x => x.CustomerRoles)
.Template(#<text>
#item.Select(r => r.Name).Aggregate((s1, s2) => string.Format("{0}, {1}", s1, s2))); // this is for display only
</text>)
.ClientTemplate("<#= CustomerRolesClientTemplate(data) #>")
.EditorTemplateName("CustomerRoles"); // this loads the editor template
// additional columns
})
// additional grid code
)
Javascript function for client template:
function CustomerRolesClientTemplate(data) {
var value = '';
var first = true;
for (var i = 0; i < data.length; i++) {
if (!first) value += ', ';
value += data.Name;
first = false;
}
return value;
}
In your Google searching, you might come across the Telerik documentation -- DON'T RELY ON THIS because it's a little out of date (it's not written for Razor and you don't need to use the [UIHint] attribute, for example).

Related

Ajax call returning old ASP.NET MVC partial view instead of updated view

I have an Ajax call triggered by a button, that calls a controller to update a partial view. The controller returns an updated partial view, but the partial view received in the success function of the Ajax call is the original view, not the updated view.
I created a sample ASP.NET MVC program to reproduce the problem. The program displays a list of customers in a table as follows.
Snapshot of UI
The text boxes are rendered in the partial view _Status. When the Toggle Status button is clicked, controller is called via Ajax to toggle the customer's status between true and false, and refresh the partial view of the corresponding text box. The problem is that the status never changes. Why is that?
UPDATE
I just added the following line of code in the Status action of the controller, and now, the Ajax success function correctly receives the updated partial view!
this.ModelState.Clear();
Can someone explain why?
Here is the Index.cshtml view that displays the initial view.
#model IEnumerable<ComboModel.Models.CustomerSummary>
<script type="text/javascript">
function updatePartialView(id) {
debugger;
$.ajax({
url: "/CustomerSummary/Status",
data: $('#' + id + ' :input').serialize(),
dataType: "HTML",
type: "POST",
success: function (partialView) {
// Here the received partial view is not the one created in
// the controller, but the original view. Why is that?
debugger;
$('#' + id).replaceWith(partialView);
},
error: function (err) {
debugger;
},
failure: function (err) {
debugger;
}
});
}
</script>
<h2>Customer Summary</h2>
<table>
<tr>
<th>Name</th>
<th>Active?</th>
<th>Toggle</th>
</tr>
#foreach (var summary in Model)
{
<tr>
<td>#summary.FirstName #summary.LastName</td>
#Html.Partial("_Status", summary.Input)
<td><button type="button" name="#("S" + summary.Input.Number)" onclick="updatePartialView(this.name)">Toggle Status</button></td>
</tr>
}
</table>
The _Status.cshtml partial view.
#model ComboModel.Models.CustomerSummary.CustomerSummaryInput
<td id="#("S" + Model.Number)">
#Html.TextBoxFor(model => model.Active)
<input type="hidden" value="#Model.Number" name="Number" />
</td>
The CustomerSummaryController.cs.
using System.Collections.Generic;
using System.Web.Mvc;
using ComboModel.Models;
namespace ComboModel.Controllers
{
public class CustomerSummaryController : Controller
{
private readonly CustomerSummaries _customerSummaries = new CustomerSummaries();
public ViewResult Index()
{
IEnumerable<CustomerSummary> summaries = _customerSummaries.GetAll();
return View(summaries);
}
public PartialViewResult Status(CustomerSummary.CustomerSummaryInput input)
{
this.ModelState.Clear(); // If I add this, things work. Why?
input.Active = input.Active == "true" ? "false" : "true";
return PartialView("_Status", input);
}
}
public class CustomerSummaries
{
public IEnumerable<CustomerSummary> GetAll()
{
return new[]
{
new CustomerSummary
{
Input = new CustomerSummary.CustomerSummaryInput {Active = "true", Number = 0},
FirstName = "John",
LastName = "Smith"
},
new CustomerSummary
{
Input = new CustomerSummary.CustomerSummaryInput {Active = "false", Number = 1},
FirstName = "Susan",
LastName = "Power"
},
new CustomerSummary
{
Input = new CustomerSummary.CustomerSummaryInput {Active = "true", Number = 2},
FirstName = "Jim",
LastName = "Doe"
},
};
}
}
}
And finally, the CustomerSummary.cs model.
namespace ComboModel.Models
{
public class CustomerSummary
{
public string FirstName { get; set; }
public string LastName { get; set; }
public CustomerSummaryInput Input { get; set; }
public class CustomerSummaryInput
{
public int Number { get; set; }
public string Active { get; set; }
}
}
}
Thanks!
This is a duplicate of Asp.net MVC ModelState.Clear.
In the current scenario, because there is no validation of the status field, it is ok to clear the ModelState. However, the MVC correct way would be to pass a status value (true or false) to a GET action in the controller, toggle the value, return the result string, and update the text box on the page.

Why does my Kendo Chart not show any data but the series are being rendered in the legen

I am working with a Kendo Chart using the MVC wrappers which I need to add series to at runtime based on data in my Model
I have verified that my model does contain valid data when the chart is about to be rendered
The view's model is a chart widget object which contains a series list
This is simply a list of chart series
Budget Chart Widget
namespace STC.Widgets.Budgeting
{
using System;
using System.Collections.Generic;
using Budget;
using Extensions;
using Helpers;
public class BudgetChartWidget
{
public BudgetChartWidget()
{
SeriesList = new List<IBudgetChartSeries>();
}
public List<IBudgetChartSeries> SeriesList { get; set; }
public string ChartTitle { get; set; }
}
}
**Budget Chart Series**
namespace STC.Widgets.Data.Budgeting
{
using System.Collections.Generic;
public class BudgetChartSeries : IBudgetChartSeries
{
public BudgetChartSeries(string seriesName)
{
Values = new List<IChartValue>();
SeriesName = seriesName;
}
public string SeriesName { get; set; }
public List<IChartValue> Values { get; set; }
}
}
Each chart series then contains values
IChartValue
namespace STC.Widgets.Data.Budgeting
{
using System;
public interface IChartValue
{
string DisplayValue { get; set; }
DateTime Period { get; set; }
double? Value { get; set; }
}
}
Partial View for chart
#using STC.Widgets.Data.Budgeting
#model STC.Widgets.Budgeting.BudgetChartWidget
<div>
#(Html.Kendo().Chart(Model.SeriesList)
.Theme((string) ViewBag.ThemeName)
.Name("BudgetViewer" + 1)
.Series(series =>
{
foreach (var item in Model.SeriesList)
{
series.Column(item.Values).Field("Value").CategoryField("DisplayValue").Name(item.SeriesName);
}
})
.Legend(legend => legend.Position(ChartLegendPosition.Bottom).Visible(true))
.ValueAxis(axis => axis.Numeric()
.MajorGridLines(lines => lines.Visible(true))
.NarrowRange(true)
.Labels(labels => labels.Format("{0:N0}"))
.Line(line => line.Visible(true))
.Crosshair(crosshair => crosshair.Visible(true)
.Tooltip(t => t.Visible(true)))
)
.CategoryAxis(axis => axis
.Labels(labels => labels.Rotation(-90))
.MajorGridLines(lines => lines.Visible(false))
.Crosshair(crosshair => crosshair.Visible(true)
.Tooltip(t => t.Visible(true)))
)
.Tooltip(tooltip => tooltip.Visible(true).Format("{0:N0}").Shared(true)))
</div>
When I run this the series are shown in the bottom legend but no data shows in the graph
I have checked and there are no Javascript errors
When I use Internet Explorer to view the source of the chart I can see that the data is there
I cant see anything wrong with the way I have created each series, I have even tried varying ways of passing the parameters.
The only one that is relevant to my situation is the one I am using
Can anyone see if I have missed something really obvious please?
Paul
I just had a similar issue, in my case the chart was not shown initially but when I clicked on the legend the chart was shown as expected. After inspecting it seems that the chart was not resizing correctly initially.
<div class="chart-wrapper">
#(Html.Kendo().Chart(...)
.....
</div>
$(document).ready(function () {kendo.resize($(".chart-wrapper"));}); seem to fix this.

MVC Validate At Least One Checkbox Or a Textbox is Selected

I have a form where either at least one checkbox must be checked OR a textbox is filled in.
I have a ViewModel that populates the CheckboxList and takes the selected values plus the textbox (other) value when required to a SelectedWasteTypes property within the ViewModel. I think my problem is I can't validate against this property as there is no form element on the view that directly relates to it. I've very new to MVC and this one has stumped me.
From the ViewModel
public List<tblWasteTypeWeb> WasteTypeWebs { get; set; }
public string WasteTypeWebOther { get; set; }
public string SelectedWasteTypes { get; set; }
View (segment)
#using (Html.BeginForm("OrderComplete", "Home"))
{
//Lots of other form elements
#for (var i = 0; i < Model.WasteTypeWebs.Count; i++)
{
var wt = Model.WasteTypeWebs[i];
#Html.LabelFor(x => x.WasteTypeWebs[i].WasteTypeWeb, wt.WasteTypeWeb)
#Html.HiddenFor(x => x.WasteTypeWebs[i].WasteTypeWebId)
#Html.HiddenFor(x => x.WasteTypeWebs[i].WasteTypeWeb)
#Html.CheckBoxFor(x => x.WasteTypeWebs[i].WasteTypeWebCb)
}
<br />
<span>
#Html.Label("Other")
#Html.TextBoxFor(x => x.WasteTypeWebOther, new { #class = "form-control input-sm" })
</span>
//More form elements
<input type="submit" value="submit" />
}
Controller Logic (if you can call it that)
[HttpPost]
public ActionResult OrderComplete(OrderViewModel model)
{
var sb = new StringBuilder();
if (model.WasteTypeWebs.Count(x => x.WasteTypeWebCb) != 0)
{
foreach (var cb in model.WasteTypeWebs)
{
if (cb.WasteTypeWebCb)
{
sb.Append(cb.WasteTypeWeb + ", ");
}
}
sb.Remove(sb.ToString().LastIndexOf(",", StringComparison.Ordinal), 1);
}
model.SelectedWasteTypes = sb.ToString();
if (!string.IsNullOrEmpty(model.WasteTypeWebOther))
{
if (!string.IsNullOrEmpty(model.SelectedWasteTypes))
{
model.SelectedWasteTypes = model.SelectedWasteTypes.TrimEnd() + ", " + model.WasteTypeWebOther;
}
else
{
model.SelectedWasteTypes = model.WasteTypeWebOther;
}
}
return View(model);
}
I very much feel I'm up a certain creek... I've thought about using JQuery, but ideally I'd like server side validation to be sure this info is captured (its a legal requirement). However, if this can only be achieved client side, I will live with it.
Any suggestions?
Take a look at the MVC Foolproof Validation Library. It has validation attributes for what you are trying to accomplish: [RequiredIfEmpty] and [RequiredIfNotEmpty]. You can also take a look at my previous SO answer about Conditional Validation.
I would suggest you to implement IValidatableObject in your ViewModel.
Inside Validate( ValidationContext validationContext) method you can check weather your conditions are met. For example:
if(string.IsNullOrWhiteSpace(WasteTypeWebOther))
yield return new ValidationResult("Your validation error here.");

Kendo UI ListView Template in MVC4

I am trying to get image files from the database and bind it to a KendoUI ListView. The problem is that it is not showing images at all.
This is what I have done:
View
<script type="text/x-kendo-tmpl" id="template">
<div class="product">
<img src="#Url.Content("#:PhotoID# + #:MIMEType#")" />
</div>
</script>
<div id="imageListView2" class="demo-section">
#(Html.Kendo().ListView<WorcesterMarble.ViewModels.PhotosViewModel>()
.Name("listView")
.TagName("div")
.ClientTemplateId("template")
.DataSource(dataSource =>
{
dataSource.Read(read => read.Action("GetImages", "StockReceiptsGrid").Data("passStockIDToListView"));
dataSource.PageSize(1);
})
.Pageable()
.Selectable(selectable => selectable.Mode(ListViewSelectionMode.Multiple))
//.Events(events => events.Change("onChange").DataBound("onDataBound"))
)
</div>
Controller
public JsonResult GetImages([DataSourceRequest] DataSourceRequest request, int stockReceiptID)
{
var photos = _stockPhotosRepository.GetStocReceiptkPhotos(stockReceiptID).ToList();
var photosList = new List<PhotosViewModel>();
//var photosList = new List<FileContentResult>();
if (photos.Count != 0)
{
foreach (var stockPhoto in photos)
{
var photoVm = new PhotosViewModel();
photoVm.PhotoID = stockPhoto.PhotoID;
photoVm.Image = stockPhoto.ImageData;
photoVm.MIMEType = stockPhoto.MIMEType;
// FileContentResult file = File(stockPhoto.ImageData, stockPhoto.MIMEType);
photosList.Add(photoVm);
}
return Json(photosList.ToList(), JsonRequestBehavior.AllowGet);
}
else
{
return null;
//FilePathResult file = this.File("/Content/Images/80.jpeg", "image/jpeg");
//return file;
}
return null;
}
Photo View Model:
public class PhotosViewModel
{
public int PhotoID { get; set; }
public byte[] Image { get; set; }
public string MIMEType { get; set; }
public int StockReceiptID { get; set; }
}
I am not sure if the problem is caused by the image url setting in the template. as you see it is not actually a url because the image is not saved anywhere except from the database. this is a screenshot of how the listview looks like; simply blank even though there must 15 images displayed!
Please let me know any clues or solutions to this problem.
I know this is a bit older, but what you need to do is change the line return Json(photosList.ToList(), JsonRequestBehavior.AllowGet); to the following:
return Json(photosList.ToDataSourceResult(request),
JsonRequestBehavior.AllowGet);
If the method ToDataSourceResult is not recognized, you have to add
using Kendo.Mvc.Extensions;
on top of your document.
It looks like you're missing a return in your controller (just before the end of your if)
return Json(photosList.ToList(), JsonRequestBehavior.AllowGet);
EDIT
Also, I noticed this:
<img src="#Url.Content("#:PhotoID# + #:MIMEType#")" />
Shouldn't that be:
<img src="#Url.Content("#:ImageData#")" />
or something similar?
It might be to late to answer, but your issue is that the json data being sent back to your view is to large so your images are not showing, rather save your images to a file and then render your images via a URL.

Replacement for TextAreaFor code in Asp.net MVC Razor

Following is my model property
[Required(ErrorMessage = "Please Enter Short Desciption")]
[StringLength(200)]
public string ShortDescription { get; set; }
And following is my corresponding View code
#Html.TextAreaFor(model => model.Product.ShortDescription, new { cols = "50%", rows = "3" })
#Html.ValidationMessageFor(model => model.Product.ShortDescription)
And this is how it shows in the browser, the way i want.
Now, since there is a bug in Microsoft's MVC3 release, I am not able to validate and the form is submitted and produces the annoying error.
Please tell me the work around or any code that can be substituted in place of TextAreaFor. I can't use EditorFor, because with it, i can't use rows and cols parameter. I want to maintain my field look in the browser. Let me know what should be done in this case
In the controller action rendering this view make sure you have instantiated the dependent property (Product in your case) so that it is not null:
Non-working example:
public ActionResult Foo()
{
var model = new MyViewModel();
return View(model);
}
Working example:
public ActionResult Foo()
{
var model = new MyViewModel
{
Product = new ProductViewModel()
};
return View(model);
}
Another possibility (and the one I recommend) is to decorate your view model property with the [DataType] attribute indicating your intent to display it as a multiline text:
[Required(ErrorMessage = "Please Enter Short Desciption")]
[StringLength(200)]
[DataType(DataType.MultilineText)]
public string ShortDescription { get; set; }
and in the view use an EditorFor helper:
#Html.EditorFor(x => x.Product.ShortDescription)
As far as the rows and cols parameters that you expressed concerns in your question about, you could simply use CSS to set the width and height of the textarea. You could for example put this textarea in a div or something with a given classname:
<div class="shortdesc">
#Html.EditorFor(x => x.Product.ShortDescription)
#Html.ValidationMessageFor(x => x.Product.ShortDescription)
</div>
and in your CSS file define its dimensions:
.shortdesc textarea {
width: 150px;
height: 350px;
}

Resources