CheckboxList in MVC3.0 - asp.net-mvc-3

How can I create a checkboxList in asp.net MVC and then to handle the event with the checkboxList

You could have a view model:
public class MyViewModel
{
public int Id { get; set; }
public bool IsChecked { get; set; }
}
A controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new[]
{
new MyViewModel { Id = 1, IsChecked = false },
new MyViewModel { Id = 2, IsChecked = true },
new MyViewModel { Id = 3, IsChecked = false },
};
return View(model);
}
[HttpPost]
public ActionResult Index(IEnumerable<MyViewModel> model)
{
// TODO: Handle the user selection here
...
}
}
A View (~/Views/Home/Index.cshtml):
#model IEnumerable<AppName.Models.MyViewModel>
#{
ViewBag.Title = "Home Page";
}
#using (Html.BeginForm())
{
#Html.EditorForModel()
<input type="submit" value="OK" />
}
and the corresponding Editor template (~/Views/Home/EditorTemplates/MyViewModel.cshtml):
#model AppName.Models.MyViewModel
#Html.HiddenFor(x => x.Id)
#Html.CheckBoxFor(x => x.IsChecked)
Now when you submit the form you would get a list of values and for each value whether it is checked or not.

There is even simpler way - use custom #Html.CheckBoxList() extension from here:
http://www.codeproject.com/KB/user-controls/MvcCheckBoxList_Extension.aspx
Usage example (MVC3 view with Razor view engine):
#Html.CheckBoxList("NAME", // NAME of checkbox list
x => x.DataList, // data source (list of 'DataList' in this case)
x => x.Id, // field from data source to be used for checkbox VALUE
x => x.Name, // field from data source to be used for checkbox TEXT
x => x.DataListChecked // selected data (list of selected 'DataList' in thiscase),
// must be of same data type as source data or set to 'NULL'
)

Related

Kendo UI Create ButtonGroup control using a viewmodel

I'm trying to find an example to create a ButtonGroup using a viewmodel.
How can I do that?
#(Html.Kendo().ButtonGroup().Name("PredictionType").Items(t =>
{
t.Add().Text("Monthly");
t.Add().Text("Weekly");
t.Add().Text("Yearly");
}))
ButtonGroup does not have a DataSource configuration item like Grid or DropDownList. Use a Razor code block in the HtmlHelper to loop over a list of items that are added. This example has the controller creating the list of items.
View - Views\Example1\Index.cshtml
#model Example.ViewModels.MySettings
#{
ViewBag.Title = "Index";
}
<div>
Prediction Type
#(Html.Kendo().ButtonGroup()
.Name("PredictionType")
.Items(t =>
{
foreach (var item in Model.PredictionTypeItems)
{
t.Add().Text(item);
}
})
)
</div>
<div>
Exponent Level
#(Html.Kendo().ButtonGroup()
.Name("ExponentLevel")
.Items(t =>
{
foreach (var item in Model.ExponentLevelItems)
{
t.Add().Text(item.ToString());
}
})
)
</div>
Model - ViewModels\MySetting.cs
using System.Collections.Generic;
namespace Example.ViewModels
{
public class MySettings
{
public IList<string> PredictionTypeItems { get; set; }
public IList<int> ExponentLevelItems { get; set; }
}
}
Controller - Controllers\Example1Controller.cs
using System.Collections.Generic;
using System.Web.Mvc;
using Example.ViewModels;
namespace Example.Controllers
{
public class Example1Controller : Controller
{
public ActionResult Index()
{
var model = new MySettings {
PredictionTypeItems = new List<string> { "Monthly", "Weekly", "Yearly" },
ExponentLevelItems = new List<int> { -2, -1, 0, 1, 2 }
};
return View(model);
}
}
}
A more robust scenario would have the items come out of a data base table.

Recommended way to implement array of Ajax cascading dropdown lists in MVC4/Razor?

I am writing an ASP.NET MVC4 / Razor / C# based application that needs to render a grid of records. Each row has several columns, and there may be 100 or so rows.
Each row has a checkbox field, text field and then three cascading dropdown lists. The first dropdown is prepopulated on page load. The second needs to be populated using Ajax on change of the first dropdown list. The third from a change on the second. Each row is separate and does not influence each other.
What is the recommended way to implement something like this? The various solutions for cascading dropdown lists are only for single cascading lists - they do not work (for me) when placed inside a foreach loop.
The skeleton of what I have is shown below:
#model IList<MyModel>
#using (Html.BeginForm("MyAction", "Home")) {
<table><tr><th>Use?</th><th>Name</th><th>List A</th><th>List B</th><th>List C</th></tr>
#Html.EditorForModel()
</table>
}
The model looks something like this:
public class MyModel
{
public bool Use { get; set; }
public string Name { get; set; }
public int? ListAId { get; set; }
public int? ListBId { get; set; }
public int? ListCId { get; set; }
public IList<ListAList> ListA { get; set; }
}
The shared EditorTemplates file MyModel.cshtml follows this structure:
#model MyNamespace.MyModel
<tr>
<td>#Html.CheckBoxFor(model => model.Use)</td>
<td>#Html.DisplayFor(model => model.Name)</td>
<td>#Html.DropDownListFor(model => model.ListAId, new SelectList(Model.ListA, "Id", "Name", Model.ListAId), "")</td>
<td>??</td>
<td>??</td>
</tr>
The ?? indicates I am unsure what to put in here.
How do I proceed to render the ListB select box using Ajax on change of the ListA select box, then on change of ListB render the ListC select box?
check this:
on select change event - Html.DropDownListFor
http://addinit.com/node/19
or
http://www.codeproject.com/Articles/258172/Simple-Implementation-of-MVC-Cascading-Ajax-Drop-D
Update1: Suppose that there is Name ROWID, (and list all the same data source).
Update2: the example available on github
Based on these responses:
How to populate a #html.dropdownlist mvc helper using JSon
Populate a <select></select> box with another
Model:
using System.Collections.Generic;
namespace MyNamespace
{
public class MyModel
{
public MyModel() { ListA = new List<ListAList>(); }
public bool Use { get; set; }
public string Name { get; set; }
public int? ListAId { get; set; }
public int? ListBId { get; set; }
public int? ListCId { get; set; }
public IList<ListAList> ListA { get; set; }
}
public class ListAList
{
public int Id { get; set; }
public string Name { get; set; }
}
}
Main action in the Home Controller:
public ViewResult MyAction()
{
var model = new List<MyModel>();
for (int i = 0; i < 10; i++)
{
var item = new MyModel()
{
Name = string.Format("Name{0}", i),
Use = (i % 2 == 0),
ListAId = null,
ListBId = null,
ListCId = null
};
for (int j = 0; j < 10; j++)
{
item.ListA.Add( new ListAList()
{
Id=j,
Name = string.Format("Name {0}-{1}",i,j)
});
}
model.Add(item);
}
return View(model);
}
Data source provider in the Home controller:
public JsonResult PopulateOption(int? listid, string name)
{
//todo: preparing the data source filter
var sites = new[]
{
new { id = "1", name = "Name 1" },
new { id = "2", name = "Name 2" },
new { id = "3", name = "Name 3" },
};
return Json(sites, JsonRequestBehavior.AllowGet);
}
EditorTemplate:
#model MyNamespace.MyModel
<tr>
<td>#Html.CheckBoxFor(model => model.Use)</td>
<td>#Html.DisplayFor(model => model.Name)</td>
<td>#Html.DropDownListFor(model => model.ListAId, new SelectList(Model.ListA, "Id", "Name", Model.ListAId), "", new { #id = string.Format("ListA{0}", Model.Name), #class="ajaxlistA" })</td>
<td><select class="ajaxlistB" id="ListB#(Model.Name)"></select></td>
<td><select class="ajaxlistC" id="ListC#(Model.Name)"></select></td>
</tr>
And the main view with Ajax functions:
#using MyNamespace
#model IList<MyModel>
#using (Html.BeginForm("MyAction", "Home")) {
<table><tr><th>Use?</th><th>Name</th><th>List A</th><th>List B</th><th>List C</th></tr>
#Html.EditorForModel()
</table>
}
<script src="#Url.Content("~/Scripts/jquery-1.7.1.js")" type="text/javascript"></script>
<script>
$(document).ready( $(function () {
$('.ajaxlistA').change(function () {
// when the value of the first select changes trigger an ajax request
list = $(this);
var listvalue = list.val();
var listname = list.attr('id');
$.getJSON('#Url.Action("PopulateOption", "Home")', { listid: listvalue, name: listname }, function (result) {
// assuming the server returned json update the contents of the
// second selectbox
var listB = $('#' + listname).parent().parent().find('.ajaxlistB');
listB.empty();
$.each(result, function (index, item) {
listB.append(
$('<option/>', {
value: item.id,
text: item.name
})
);
});
});
});
$('.ajaxlistB').change(function () {
// when the value of the first select changes trigger an ajax request
list = $(this);
var listvalue = list.val();
var listname = list.attr('id');
$.getJSON('#Url.Action("PopulateOption", "Home")', { listid: listvalue, name: listname }, function (result) {
// assuming the server returned json update the contents of the
// second selectbox
var listB = $('#' + listname).parent().parent().find('.ajaxlistC');
listB.empty();
$.each(result, function (index, item) {
listB.append(
$('<option/>', {
value: item.id,
text: item.name
})
);
});
});
});
}));
</script>
And the result:

Dropdown list in Webgrid

Can somebody help me how can I put a dropdownlist in my webgrid column.
I need to bind my dropdown list to a list from Model. And need to select an item from the list for every corresonding record in the grid.
And I should be able to post selcetd values to the controller.
I have tried solutions givine in few links Dropdownlist propbelm in mvc3 and few othres.
I am pasting my sample code.
Model:
public class AllocateToStore
{
public IList<OrderLine> FailureAllocations { get; set; }
public IList<SelectListItem> AllocationStatus
{
get
{
// code to fetch list.
}
}
}
public class OrderLine
{
public long Id { get; set; }
public DateTime Date { get; set; }
public int Status { get; set; }
}
Controller:
public ActionResult AutoAllocate()
{
// This action will load the view with data.
// Get model data and send it to view.
return View("Allocated",model);
}
[HttpPost]
public ActionResult ResolveUnallocatedOrders(AllocateToStore coll)
{
// When user changes the selection in grid and post the page I need to get the selection // here. So that I can update that record.
return null;
}
And view is
#model AllocateToStore
#{
ViewBag.Title = "Orders";
}
#{
var grid = new WebGrid(Model.FailureAllocations, rowsPerPage: 100);
}
#using (Html.BeginForm("ResolveUnallocatedOrders", "OrderProcessing", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
if (Model.FailureAllocations.Any())
{
<div>
#grid.GetHtml(
columns: grid.Columns(
grid.Column(columnName: "Order date", header: "Order Date", format: item => item.Order.Date),
grid.Column("dropdown", header: "Resolution", format:
#<span>
#{ var index = Guid.NewGuid().ToString(); }
#Html.Hidden("Status.Index", index)
#Html.DropDownList("Status[" + index + "].SelectedValue", Model.AllocationStatus)
</span>
)
),
tableStyle: "expandable-table",
htmlAttributes: new { id = "gridFailureAllocations" }
)
<br />
<input type="submit" value="Resolve" id="resolve-button" />
</div>
}
}
Thanks,
Naresh
The following should work:
<div>
#grid.GetHtml(
columns: grid.Columns(
grid.Column(columnName: "Date", header: "Order Date"),
grid.Column("dropdown", header: "Resolution", format:
#<span>
#{ var index = Guid.NewGuid().ToString(); }
#Html.Hidden("FailureAllocations.Index", index)
#Html.Hidden("FailureAllocations[" + index + "].Id", (long)item.Id)
#Html.DropDownList("FailureAllocations[" + index + "].Status", Model.AllocationStatus)
</span>
)
),
tableStyle: "expandable-table",
htmlAttributes: new { id = "gridFailureAllocations" }
)
<br />
<input type="submit" value="Resolve" id="resolve-button" />
</div>
and then inside your ResolveUnallocatedOrders controller action you could use coll.FailureAllocations to retrieve the corresponding values:
[HttpPost]
public ActionResult ResolveUnallocatedOrders(AllocateToStore coll)
{
// coll.FailureAllocations will contain the necessary data
...
}
Remark: you could include an additional hidden field for the Order.Date field if you want to retrieve its value back in the POST action.

Simple Ajax in asp.net MVC 3, update the model and rerender part

I come from a more WPF application background and I'm used to bindings and such. Jumping into websites then can come with it's problems as they work so much more differently.
I'm trying to do a simple Ajax action but not sure where to begin. Basically I want to make a dropdownlist that changes one property on the model and re-renders that part of the page. Perhaps this is too much of a WPF way to do this so my Model could be twisted for the thing it is supposed to do.
Here is what I got already:
public class TheViewModel
{
private IEnumerable<TheData> _data;
public TheViewModel(IEnumerable<TheData> data)
{
_data = data;
Year = 2012;
}
public int Year { get; set; }
public ICollection<TheData> Data
{
get
{
return _data.Where(d => d.Year == this.Year).ToList();
}
}
public IEnumerable<SelectListItem> YearList
{
// lists the available years
}
}
public class TheData
{
public int Year { get; set; }
//Some more info I want to represent in Table
}
And the razor:
#using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "thetable" }))
{
#Html.DropDownListFor(model => model.Year, Model.YearList, new { AutoPostBack = "true"})
<input type="submit" name="name" value="Submit" />
}
<table id="thetable">
<thead>
//some headers
</thead>
<tbody>
#foreach ( var item in Model.Data)
{
//row for each data
}
</tbody>
</table>
As you can see I'm hoping for the Year property to be updated and a new call to be made for the Data property which would result in new information. That information would be rendered in thetable Table
Here's a full example.
Model:
public class MyViewModel
{
public int Year { get; set; }
public IEnumerable<SelectListItem> Years
{
get
{
return Enumerable.Range(1980, 40).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = x.ToString()
});
}
}
public IList<TheData> Data { get; set; }
}
public class TheData
{
public int Year { get; set; }
public string Foo { get; set; }
public string Bar { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(int year)
{
var model = new[]
{
new TheData { Year = year, Foo = "foo 1", Bar = "bar 1" },
new TheData { Year = year, Foo = "foo 2", Bar = "bar 2" },
new TheData { Year = year, Foo = "foo 3", Bar = "bar 3" },
};
return PartialView("_data", model);
}
}
Index.cshtml view:
#model MyViewModel
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#yearsddl').change(function () {
$(this).closest('form').trigger('submit');
});
});
</script>
#using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "data" }))
{
#Html.DropDownListFor(x => x.Year, Model.Years, new { id = "yearsddl" })
}
<table>
<thead>
<tr>
<th>Year</th>
<th>Foo</th>
<th>Bar</th>
</tr>
</thead>
<tbody id="data">
#Html.Partial("_data", Model.Data ?? Enumerable.Empty<TheData>())
</tbody>
</table>
The jquery.unobtrusive-ajax.js script inclusion should be moved out of the index view inside the layout for example and the custom js that subscribes for the change event of the dropdownlist should be moved into a separate js file and included from the Layout. I just put them here to illustrate a full example of what's required for the view to work.
_Data.cshtml partial:
#model IList<TheData>
#for (int i = 0; i < Model.Count; i++)
{
<tr>
<td>#Html.DisplayFor(x => x[i].Year)</td>
<td>#Html.DisplayFor(x => x[i].Foo)</td>
<td>#Html.DisplayFor(x => x[i].Bar)</td>
</tr>
}

MVC3- Radion Button Grouping and Binding from database

How to get the radio button options from database using in MVC3 Razor. I have 4 options for each question, the options should be populated from the database and should be grouped.
#Html.RadioButtonFor(model => Model.AAAa, 'Y', new { title = "Please check this if AAA has been updated" })
Yes
This gives me hard coded value as Yes but text needs to be populated with DB Table.
How would I bind it back the selected value back to the database?. An Example would be more helpful.
Thank you
As always you start by defining a view model that will represent the information you will be dealing with in the view:
public class MyViewModel
{
public string SelectedValue { get; set; }
// In your question you seem to be dealing with a title attribute as well
// If this is the case you could define a custom view model ItemViewModel
// which will contain the Value, the Text and the Title properties for
// each radio button because the built-in SelectListItem class that I am using here
// has only Value and Text properties
public SelectListItem[] Items { get; set; }
}
then you write a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// Obviously those will come from your database or something
Items = new[]
{
new SelectListItem { Value = "Y", Text = "Yes" },
new SelectListItem { Value = "N", Text = "No" },
new SelectListItem { Value = "D", Text = "Dunno" }
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
then a corresponding view:
#model MyViewModel
#using (Html.BeginForm())
{
for (int i = 0; i < Model.Items.Count; i++)
{
#Html.RadioButtonFor(x => x.SelectedValue, Model.Items[i].Value, new { id = "item_" + i })
#Html.Label("item_" + i, Model.Items[i].Text)
<br/>
}
<button type="submit">OK</button>
}
or to make the view less messy you could write a custom HTML helper that will render those radio buttons for you:
public static class HtmlExtensions
{
public static IHtmlString RadioButtonListFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> items
)
{
var sb = new StringBuilder();
var i = 0;
foreach (var item in items)
{
var id = string.Format("item{0}", i++);
var radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = id });
var label = htmlHelper.Label(id, item.Text);
sb.AppendFormat("{0}{1}<br/>", radio, label);
}
return new HtmlString(sb.ToString());
}
}
and now your view will simply become:
#model MyViewModel
#using (Html.BeginForm())
{
#Html.RadioButtonListFor(x => x.SelectedValue, Model.Items)
<button type="submit">OK</button>
}
which obviously is nicer to look.

Resources