MVC3- Radion Button Grouping and Binding from database - asp.net-mvc-3

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.

Related

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:

how to register onclick event to #Html.RadioButtonForSelectList in asp.net mvc 3.0

My Model
public class IndexViewModel
{
public IEnumerable<SelectListItem> TestRadioList { get; set; }
[Required(ErrorMessage = "You must select an option for TestRadio")]
public String TestRadio { get; set; }
[Required(ErrorMessage = "You must select an option for TestRadio2")]
public String TestRadio2 { get; set; }
}
public class aTest
{
public Int32 ID { get; set; }
public String Name { get; set; }
}
My Controller
public ActionResult Index()
{
List<aTest> list = new List<aTest>();
list.Add(new aTest() { ID = 1, Name = "Yes" });
list.Add(new aTest() { ID = 2, Name = "No" });
list.Add(new aTest() { ID = 3, Name = "Not applicable" });
list.Add(new aTest() { ID = 3, Name = "Muttu" });
SelectList sl = new SelectList(list, "ID", "Name");
var model = new IndexViewModel();
model.TestRadioList = sl;
return View(model);
}
My View
#using (Html.BeginForm()) {
<div>
#Html.RadioButtonForSelectList(m => m.TestRadio, Model.TestRadioList)
</div>
}
Helper method
public static class HtmlExtensions
{
public static MvcHtmlString RadioButtonForSelectList<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> listOfValues)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var sb = new StringBuilder();
if (listOfValues != null)
{
// Create a radio button for each item in the list
foreach (SelectListItem item in listOfValues)
{
// Generate an id to be given to the radio button field
var id = string.Format("{0}_{1}", metaData.PropertyName, item.Value);
// Create and populate a radio button using the existing html helpers
var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text));
var radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = id }).ToHtmlString();
// Create the html string that will be returned to the client
// e.g. <input data-val="true" data-val-required="You must select an option" id="TestRadio_1" name="TestRadio" type="radio" value="1" /><label for="TestRadio_1">Line1</label>
sb.AppendFormat("<div class=\"RadioButton\">{0}{1}</div>", radio, label);
}
}
return MvcHtmlString.Create(sb.ToString());
}
}
Here is the code i'm using... not sure how to give a onclick event for the control. In the helper method i could not find any appropriate htmlattributes parameter. as per my requirement. on click of any radiobutton in the list i need to call a js function with few parameters. which i'm not able to do. Someonce please help. Thanks in advance.
I haven't got the means to test this at the moment, but a rough idea is adding IDictionary htmlAttributes to the method and passing it in there. If you dont have the required onClick code in the view, then you could omit the parameter and do it in the extension method
public static class HtmlExtensions
{
public static MvcHtmlString RadioButtonForSelectList<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> listOfValues,
IDictionary<string, Object> htmlAttributes)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var sb = new StringBuilder();
if (listOfValues != null)
{
// Create a radio button for each item in the list
foreach (SelectListItem item in listOfValues)
{
// Generate an id to be given to the radio button field
var id = string.Format("{0}_{1}", metaData.PropertyName, item.Value);
// Create and populate a radio button using the existing html helpers
var label = htmlHelper.Label(id, HttpUtility.HtmlEncode(item.Text));
htmlAttributes["id"] = id;
var radio = htmlHelper.RadioButtonFor(expression, item.Value, htmlAttributes).ToHtmlString();
// Create the html string that will be returned to the client
// e.g. <input data-val="true" data-val-required="You must select an option" id="TestRadio_1" name="TestRadio" type="radio" value="1" /><label for="TestRadio_1">Line1</label>
sb.AppendFormat("<div class=\"RadioButton\">{0}{1}</div>", radio, label);
}
}
return MvcHtmlString.Create(sb.ToString());
}
}
and then call it using something like:
#Html.RadioButtonForSelectList(m => m.TestRadio, Model.TestRadioList, new { onclick="someFunction();" })
alternatively you could set a css class and bind to the click event. for example,
<script type="text/javascript>
$('.someClassName').click( function() {
alert('clicked');
});
</script>
#Html.RadioButtonForSelectList(m => m.TestRadio, Model.TestRadioList, new { #class="someClassName" })

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.

Problems with MVC 3 DropDownList() in WebGrid()

I'm trying to place a DropDownList inside a WebGrid but I can't figure out how to do it :(
Things I've tried:
grid.Column("Id", "Value", format: ((item) =>
Html.DropDownListFor(item.SelectedValue, item.Colors)))
and
grid.Column(header: "", format: (item => Html.DropDownList("Colors", item.Colors)))
and
grid.Column(header: "", format: Html.DropDownList("Colors"))
and various others but I couldn't get it to work.
Any help is much appreciated.
Model
public class PersonViewModel
{
public string Name { get; set; }
public int Age { get; set; }
public SelectList Colors { get; set; }
public int SelectedValue { get; set; }
}
public class ColorViewModel
{
public int ColorID { get; set; }
public string ColorName { get; set; }
}
Controller
public ActionResult Index()
{
var colorList = new List<ColorViewModel>() {
new ColorViewModel() { ColorID = 1, ColorName = "Green" },
new ColorViewModel() { ColorID = 2, ColorName = "Red" },
new ColorViewModel() { ColorID = 3, ColorName = "Yellow" }
};
var people = new List<PersonViewModel>()
{
new PersonViewModel() {
Name = "Foo",
Age = 42,
Colors = new SelectList(colorList)
},
new PersonViewModel() {
Name = "Bar",
Age = 1337,
Colors = new SelectList(colorList)
}
};
return View(people);
}
View
#model IEnumerable<PersonViewModel>
#{
var grid = new WebGrid(Model);
}
<h2>DropDownList in WebGrid</h2>
#using (Html.BeginForm())
{
#grid.GetHtml(
columns: grid.Columns(
grid.Column("Name"),
grid.Column("Age"),
grid.Column() // HELP - INSERT DROPDOWNLIST
)
)
<p>
<button>Submit</button>
</p>
}
grid.Column(
"dropdown",
format: #<span>#Html.DropDownList("Color", (SelectList)item.Colors)</span>
)
Also in your controller make sure you set the value and text properties of your SelectList and instead of:
Colors = new SelectList(colorList)
you should use:
Colors = new SelectList(colorList, "ColorID", "ColorName")
Also it seems a bit wasteful to me to define the same SelectList for all row items especially if they contain the same values. I would refactor your view models a bit:
public class MyViewModel
{
public IEnumerable<SelectListItem> Colors { get; set; }
public IEnumerable<PersonViewModel> People { get; set; }
}
public class PersonViewModel
{
public string Name { get; set; }
public int Age { get; set; }
public int SelectedValue { get; set; }
}
and then:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// define the values used to render the dropdown lists
// for each row
Colors = new[]
{
new SelectListItem { Value = "1", Text = "Green" },
new SelectListItem { Value = "2", Text = "Red" },
new SelectListItem { Value = "3", Text = "Yellow" },
},
// this is the collection we will be binding the WebGrid to
People = new[]
{
new PersonViewModel { Name = "Foo", Age = 42 },
new PersonViewModel { Name = "Bar", Age = 1337 },
}
};
return View(model);
}
}
and in the view:
#model MyViewModel
#{
var grid = new WebGrid(Model.People);
}
<h2>DropDownList in WebGrid</h2>
#using (Html.BeginForm())
{
#grid.GetHtml(
columns: grid.Columns(
grid.Column("Name"),
grid.Column("Age"),
grid.Column(
"dropdown",
format: #<span>#Html.DropDownList("Color", Model.Colors)</span>
)
)
)
<p>
<button>Submit</button>
</p>
}
UPDATE:
And since I suspect that you are not putting those dropdownlists for painting and fun in your views but you expect the user to select values inside them and when he submits the form you might wish to fetch the selected values, you will need to generate proper names of those dropdown lists so that the default model binder can automatically retrieve the selected values in your POST action. Unfortunately since the WebGrid helper kinda sucks and doesn't allow you to retrieve the current row index, you could use a hack as the Haacked showed in his blog post:
grid.Column(
"dropdown",
format:
#<span>
#{ var index = Guid.NewGuid().ToString(); }
#Html.Hidden("People.Index", index)
#Html.DropDownList("People[" + index + "].SelectedValue", Model.Colors)
</span>
)
Now you could have a POST controller action in which you will fetch the selected value for each row when the form is submitted:
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// the model variable will contain the People collection
// automatically bound for each row containing the selected value
...
}
..make my dropdown list to select a value from the list when it loads.The following works for sure. I have tried it out myself. Any questions keep me posted.
#Html.DropDownList("RejectReason", Model.SalesReasonList.Select(u => new SelectListItem
{
Text = u.Text,
Value = u.Value,
Selected = u.Value ==#item.RejectReason
}))

CheckboxList in MVC3.0

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'
)

Resources