decrease load time of form with many list boxes - asp.net-mvc-3

I have a form that can have as many as 400 list boxes, each list box can have as many as 900 items. The form is created using a foreach loop:
foreach(var i in Model)
{
var selectList = Model.OrderBy(m => m.Name)
.Select(m => new SelectListItem
{
Text = m.Name,
Value = m.Id.ToString(),
}).ToList();
#Html.ListBox(i+"ListBox", selectList, new { #class = "multiselect", size = "12", multiple = "true", })
}
when this loop is removed the page loads 4x faster.
Is there anyway to do this that will reduce the load time of the page?

Related

How can i highlight the Kendo grid cell by color change after update

I am using Kendo Ui Grid with MVC and SignalR. I can successfully perform the CRUD operations on grid using SignalR. I would like to notify clients by highlighting(By changing cell color) the updated cell. How can I achieve this with the following code:
#(Html.Kendo().Grid<Webapplication1.Models.ShipViewModel>()
.Name("ShipGrid")
.Columns(c =>{
c.Bound(m => m.Id).Hidden();
c.Bound(m => m.LocationViewModel)
.Title("Location1");
c.Bound(m => m.Location2ViewModel)
.Title("Location2");
c.Bound(m => m.boxSent);
c.Command(p =>
{
p.Edit().Text(" ").UpdateText(" ").CancelText(" ");
p.Destroy().Text(" ").HtmlAttributes(new { #title = "Cancel" });
});
})
.ToolBar(toolbar =>
{
toolbar.Create().Text("").HtmlAttributes(new { #title = "Add" });
})
.Editable(editable => editable
.DisplayDeleteConfirmation("DELETE.")
.Mode(Kendo.Mvc.UI.GridEditMode.PopUp)
.TemplateName("abcEditor")
)
.Events(events =>
{
events.Edit("edit");
})
.DataSource(dataSource => dataSource
.SignalR()
.Transport(tr => tr
.Promise("hubStart")
.Hub("mainHub")
.Client(c => c.Read("abc_Read").Create("abc_Insert").Update("abc_Update").Destroy("abc_Delete"))
.Server(s => s.Read("abc_Read").Create("abc_Insert").Update("abc_Update").Destroy("abc_Delete")))
.Schema(schema => schema
.Model(m => {
m.Id(p => p.Id);
m.Field(p => p.Location1ViewModel).DefaultValue(ViewData["DefaultLocation1"] as Webapplication1.Models.Location1ViewModel);
m.Field(p => p.Location2ViewModel).DefaultValue(ViewData["DefaultLocation2"] as Webapplication1.Models.DeliveryLocationViewModel);
})
)
)
)
I would like to Highlight the cell that is being updating here. Something like stock market data flashing. How can I achieve this?
I've done similar kind of thing. I don't know if that helps you. In your default view model add a extra property, say "Updated" as a boolean. Now every time you have update a row, put "Updated" as a true.
And in kendo grid add a new dataBound event.
.Events(events => events.DataBound("onDataBound"))
Now on JS use something like the following;
function onDataBound(arg) {
var itemsInActivityGrid = $("#ShippingGrid").data().kendoGrid.dataSource.data().length;
for (i = 0; i < itemsInActivityGrid; i++) {
if ($("#ShippingGrid").data().kendoGrid.dataSource.data()[i].Updated == true) {
$("#ShippingGrid .k-grid-content tr[data-uid='" + $("#ShippingGrid").data().kendoGrid.dataSource.data()[i].uid + "']").css("background-color", "orange");
}
}
}
Update: I don't know your logic. As far as you put on comments, you want to do something like online share dealing sites. Anyway, as far as I could, if you want to highlight individual cell in a row, add another extra field say "Column" along with "Updated"; it could be a string. Here you mark which cell you want to put the back ground colour from the backend. Say we've got it's value as "2".
for (i = 0; i < itemsInActivityGrid; i++)
{
var TableUID = $("#ShippingGrid").data().kendoGrid.dataSource.data()[i].uid;
var TableToColour = $("#ShippingGrid .k-grid-content tr[data-uid='" + TableUID + "']").parent().parent()[0];
var ColumnToColor = $("#ShippingGrid").data().kendoGrid.dataSource.data()[i].Column;
$(TableToColour.rows[0].cells[" + ColumnToColor + "]).select().attr("style","background-color:blue")
}
In case, you need to highlight multiple cells on the same row, in Column send something like "1,2,3,5"; where 1, 2, 3 and 5 represents the column numbers on the same row. And after ColumnToColor do some string parsing, put it into a for loop or something and colour;
Hope this helps. Thank you.
I have achieved this as below and its working fine:
in my .cshtml page
myHub.client.highlightRow = function (id) {
var data = $("#MyGrid").data("kendoGrid").dataSource.data();
for (var i = 0; i < data.length; i++) {
var dataItem = data[i];
if (dataItem.id == id) {
//alert(dataItem.uid);
$("#MyGrid").data("kendoGrid").tbody.find("tr[data-uid=" + dataItem.uid + "]").effect("highlight", { color: "#f35800" }, 3000);
}
}
};
And in my update/insert method in my SignalR Hub class:
Clients.Others.highlightRow(mygridViewModel.Id);

Kendo Pie Chart to Bar Chart

I am trying to go from a Kendo Pie chart to a Kendo Bar chart, my issue is the bar chart only returns one piece of data.
cshtml
`
<div id="pieEmployeeContainer">
#(Html.Kendo().Chart<SalesChart>().Name("pieEmployee").HtmlAttributes(new { style = "width: 90%;", #class = "fpos-chart" })
.Title("Top 10")
.Legend(false)
.Theme("bootstrap")
.DataSource(ds => ds.Read("SM_GetSalesByEmployees", "Home"))
.Series(s => s
.Pie(m => m.Total, m => m.Category)
.Padding(0)
)
.Tooltip(t => t
.Visible(true)
.Format("{0:c}")
.Template("#= category # <br /> #= kendo.format('{0:c}', value) # (#= kendo.format('{0:p}', percentage)#)")
)
.Events(e => e.SeriesClick("getByEmployee"))
.Deferred()
)
</div>
`
Controller
public ActionResult SM_GetSalesByEmployees()
{
List<SalesChart> items;
List<SalesChart> salesByEmpl;
using (StreamReader r = new StreamReader("C:\\Development\\Back Office Web\\Sandbox\\BackOffice.Web\\BackOffice.Web\\Content\\Data\\SalesByEmployee.json"))
{
string json = r.ReadToEnd();
items = JsonConvert.DeserializeObject<List<SalesChart>>(json);
salesByEmpl = items.GroupBy(l => l.EmployeeName)
.Select(lg =>
new SalesChart
{
Category = lg.Key,
Total = lg.Sum(w => w.Total)
}).ToList();
}
return new CustomJsonResult
{
Data = salesByEmpl
};
}
script
function getByEmployee(e)
{
var categorySelected = e.category;
var chart = $("#pieEmployee").data("kendoChart");
$.post("Home/GetSalesByEmployee?EmpName=" + categorySelected, function (results) {
chart.setDataSource(new kendo.data.DataSource({ data: results }));
});
chart.options.series[0].type = "bar";
chart.options.series[0].ValueAxis = "${Total}";
chart.options.series[0].categoryAxis = "{Category}";
chart.options.categoryAxis.baseUnit = "months";
chart.refresh();
}
I dont have a good enough reputation to post images, sorry about that.
The bar chart is only getting one data point and displaying that, rather than showing all data.
Any help is greatly appreciated.
I can't build out any test stuff but from quickly looking at it, the data format for the pie chart needs to be changed. It needs to be in percentages (the whole series needs to = 100) so you'll need to convert the data either in the view or the controller.

How to add dummy values to a dropdownlist in MVC3

I am following few tutorials for creating MVC3 application.
I saw example of adding dropdownlist bound to a model.
#Html.DropDownListFor(model => model.Vehicle.Model, new List<SelectListItem>(), String.Empty, new { style = "width: 100px;", size = "1" })
But i just want to add few contant values i.e. not coming from the DB, but just want to add few items to dropdownlist in code, how can i do it?
#{
var modellist = new List<VehicleModels>()
{
new VehicleModels() { ID= 1, Name="A"},
new VehicleModels() { ID= 2, Name="B"},
new VehicleModels() { ID= 3, Name="C"},
new VehicleModels() { ID= 4, Name="D"}
}
}
#Html.DropDownListFor(model => model.Vehicle.Model, new SelectList(modellist, "ID" , "Name"), String.Empty, new { style = "width: 100px;", size = "1" })

MultiSelectList does not highlight previously selected items

In a ASP.NET MVC (Razor) project, I'm using a ListBox with Multi Select option in a Edit View,
CONTROLLER
public ActionResult Edit(int id)
{
Post post = db.Posts.Find(id);
string selectedValues = post.Tags; //This contains Selected values list (Eg: "AA,BB")
ViewBag.Tagslist = GetTags(selectedValues.Split(','));
return View(post);
}
private MultiSelectList GetTags(string[] selectedValues)
{
var tagsQuery = from d in db.Tags
orderby d.Name
select d;
return new MultiSelectList(tagsQuery, "Name", "Name", selectedValues);
}
HTML
<div class="editor-field">
#Html.ListBox("Tags", ViewBag.Tagslist as MultiSelectList)
</div>
This loads the items (Tag List) in to ListBox, but does not highlight the items in the Selected Values list.
How to fix this issue?
Thanks in advance.
I suspect that your Post class (to which your view is strongly typed) has a property called Tags. You also use Tags as first argument of the ListBox helper. This means that the helper will look into this property first and ignore the selected values you passed to the MultiSelectList. So the correct way to set a selected value is the following:
public ActionResult Edit(int id)
{
Post post = db.Posts.Find(id);
ViewBag.Tagslist = GetTags();
return View(post);
}
private MultiSelectList GetTags()
{
var tagsQuery = from d in db.Tags
orderby d.Name
select d;
return new MultiSelectList(tagsQuery, "Name", "Name");
}
and in the view:
<div class="editor-field">
#Html.ListBoxFor(x => x.Tags, ViewBag.Tagslist as MultiSelectList)
</div>
And here's a full example that should illustrate:
public class HomeController : Controller
{
public ActionResult Index()
{
var post = new Post
{
Tags = new[] { "AA", "BB" }
};
var allTags = new[]
{
new { Name = "AA" }, new { Name = "BB" }, new { Name = "CC" },
};
ViewBag.Tagslist = new MultiSelectList(allTags, "Name", "Name");
return View(post);
}
}
Also I would recommend you using view models instead of passing your domain entities to the view. So in your PostViewModel you will have a property called AllTags of type MultiSelectList. This way you will be able to get rid of the weak typed ViewBag.

How can I display an array model property as a list in my view?

I have this array property in my model and would like to see it in my view as a dropdown list. Here's the array property:
public string[] weekDays = new string[5] { "monday", "Tuesday", "Wednesday", "Thursday", "Friday" };
public string[] WeekDays
{
get { return weekDays; }
}
I've look for hours with no simple explanation or examples. Please help.
You can use DropDownList() html helper.
Html.DropDownList("weekDays",
Model.WeekDays.Select(s => new SelectListItem { Text = s }))
If you want to read the selected value you can use DropDownListFor() helper.
Html.DropDownListFor(model => model.SelectedWeekDay, //a property to assign the value
Model.WeekDays.Select(s => new SelectListItem { Text = s, Value = s }))
Here's how I solved it.
#{
var wekdys = new Enrollment();
#Html.DropDownList("weekDays", wekdys.WeekDays.Select(s => new SelectListItem { Text = s.ToString(), Value = s.ToString() }))
}
this allows me to have a DropDownList outside of the foreach loop

Resources