In partial view
I work with textboxes like this.
#model Dictionary<string, string>
#Html.TextBox("XYZ", #Model["XYZ"])
How can i generate radiobuttons, and get the desired value in the form collection as YES/NO True/False) ? Currently i am getting null for "ABC" if i select any value for the below.
<label>#Html.RadioButton("ABC", #Model["ABC"])Yes</label>
<label>#Html.RadioButton("ABC", #Model["ABC"])No</label>
Controller
public int Create(int Id, Dictionary<string, string> formValues)
{
//Something Something
}
In order to do this for multiple items do something like:
foreach (var item in Model)
{
#Html.RadioButtonFor(m => m.item, "Yes") #:Yes
#Html.RadioButtonFor(m => m.item, "No") #:No
}
Simply :
<label>#Html.RadioButton("ABC", True)Yes</label>
<label>#Html.RadioButton("ABC", False)No</label>
But you should always use strongly typed model as suggested by cacho.
I done this in a way like:
#Html.RadioButtonFor(model => model.Gender, "M", false)#Html.Label("Male")
#Html.RadioButtonFor(model => model.Gender, "F", false)#Html.Label("Female")
I solve the same problem with this SO answer.
Basically it binds the radio button to a boolean property of a Strongly Typed Model.
#Html.RadioButton("blah", !Model.blah) Yes
#Html.RadioButton("blah", Model.blah) No
Hope it helps!
MVC5 Razor Views
Below example will also associate labels with radio buttons (radio button will be selected upon clicking on the relevant label)
// replace "Yes", "No" --> with, true, false if needed
#Html.RadioButtonFor(m => m.Compatible, "Yes", new { id = "compatible" })
#Html.Label("compatible", "Compatible")
#Html.RadioButtonFor(m => m.Compatible, "No", new { id = "notcompatible" })
#Html.Label("notcompatible", "Not Compatible")
<label>#Html.RadioButton("ABC", "YES")Yes</label>
<label>#Html.RadioButton("ABC", "NO")No</label>
MVC Razor provides one elegant Html Helper called RadioButton with two parameters (this is general, But we can overload it uptil five parameters) i.e. one with the group name and other being the value
<div class="col-md-10">
Male: #Html.RadioButton("Gender", "Male")
Female: #Html.RadioButton("Gender", "Female")
</div>
<p>#Html.RadioButtonFor(x => x.type, "Item1")Item1</p>
<p>#Html.RadioButtonFor(x => x.type, "Item2")Item2</p>
<p>#Html.RadioButtonFor(x => x.type, "Item3")Item3</p>
This works for me.
#{ var dic = new Dictionary<string, string>() { { "checked", "" } }; }
#Html.RadioButtonFor(_ => _.BoolProperty, true, (#Model.BoolProperty)? dic: null) Yes
#Html.RadioButtonFor(_ => _.BoolProperty, false, (!#Model.HomeAddress.PreferredMail)? dic: null) No
I wanted to share one way to do the radio button (and entire HTML form) without using the #Html.RadioButtonFor helper, although I think #Html.RadioButtonFor is probably the better and newer way (for one thing, it's strongly typed, so is closely linked to theModelProperty). Nevertheless, here's an old-fashioned, different way you can do it:
<form asp-action="myActionMethod" method="post">
<h3>Do you like pizza?</h3>
<div class="checkbox">
<label>
<input asp-for="likesPizza"/> Yes
</label>
</div>
</form>
This code can go in a myView.cshtml file, and also uses classes to get the radio-button (checkbox) formatting.
Related
I have an html dropdownlistfor which is being populated from my database, this I was able to do successfully but the issue I am having now is including an additional option not available in the database as an option that can also be selected.it is actually a list of items but I want a give an option ALL which when selected means the user is selecting all the items displayed in the database, my major issue is how to include the ALL option. I have searched and read similar questions but they are not what am trying to achieve. thanks for your help. here is my code
in my controller I have this:
var load = from bh in db.IV_001_ITEM
select bh;
ViewBag.selection = new SelectList(load.ToList(), "item_code", "item_name", glay.vwstring2);
in my view I have this:
<div class="col-sm-2">
#Html.DropDownListFor(m => m.vwstring2, ViewBag.selection as SelectList, "Select", new { #class = "form-control", required = "required", id = "selectc" } )
</div>
You can use the Add method to explicitly add an extra option (SelectListItem)
List<SelectListItem> optionList = db.IV_001_ITEM
.Select(x=>new SelectListItem { Value=x.item.code,
Text=x.itemName}).ToList();
// Now add the item you want
optionList.Add(new SelectListItem { Value="Foo",Text="Bar"});
//use this now
ViewBag.Items = optionList;
// You can set the selected item on your view model property
myViewModelObject.vwstring2 = glay.vwstring2; //For the selected item
return View(myViewModelObject);
In your view,
#Html.DropDownListFor(m => m.vwstring2, ViewBag.Items as List<SelectListItem>,
"Select", new { #class = "form-control"})
Could some please convert the following code to a standard html tag? Something like <select id="selectDomain" name="selectDomain">, IF it converts to a select tag.
#Html.DropDownListFor(x => x.domain, Enumerable.Empty<SelectListItem>(), "", new { id = "selectDomain", name = "selectDomain"})
If I understand correctly, doesn't x => x.domain mean id="domain" name="domain"? Is this code overwriting the name and id to selectDomain?
Finally, if it isn't convertible to an html tag, I want to add a class to the given code. I tried adding it inside the new{} like new{id="selectDomain", name="selectDomain", class="form-control"} section but it gave me error saying expected }
You understand correctly if you write:
#Html.DropDownListFor(x => x.domain, Enumerable.Empty<SelectListItem>())
Razor will produce:
<select id="domain" name="domain"> </select>
It's better to use ViewModel and create property selectDomain in it and then:
#Html.DropDownListFor(x => x.selectDomain, Enumerable.Empty<SelectListItem>(), new { #class="form-control" })
Will make html that you want.
But if you don't want to do it you can use Html.DropDownList helper like this:
#Html.DropDownList("selectDomain",Enumerable.Empty<SelectListItem>(), new { #class="form-control" })
note escaped class with # symbol.
You can specify "name" with uppercase first letter (works in MVC5)
#Html.DropDownListFor(x => x.domain, Enumerable.Empty<SelectListItem>(), "", new { id = "selectDomain", Name = "selectDomain"})
result:
<select name="selectDomain" id="selectDomain">
I found posts for populating from database, classes, xml, etc but I cannot seem to find one for populating a dropdownlist straight from the web page.
<div class="editor-field">
#Html.DropDownListFor(x => x.Subject, Model.SubjectList)
#Html.ValidationMessageFor(m => m.Subject)
</div>
I just want to add several items to my dropdownlist without using Model.
Is that possible?
I think I understand what you are asking here. If you just want to hardcode values in the view you can do something like this:
#Html.DropDownList("", new List<SelectListItem> {
new SelectListItem { Text = "Option 1", Value="1"},
new SelectListItem{Text="Option 2", Value="1"}})
You could also create the select list in the controller and store it in the ViewBag.
I have a case where I have a page displaying an order and tabs that display the order details. The order details are quite complex and since they are the same layout, I want to use a partial view or editor template that will generate the form.
The problem is the result is multiple duplicate form input id's are generated (one for each order detail. For example, I have:
foreach (var orderDetail in Model.OrderDetils)
{
#Html.EditorFor(model => orderDetail, "WorkOrder", orderDetail)
}
I've read much about this and see solutions where it is recommended to use an editortemplate, but that solution only works when you have the same form to render, but passing it different model properties so the control id's prefixes will differ...ie. like this solution.
In my case, this won't work as the model property I am passing is always the same.
So how else can I create unique Id's in the partial or editor template that will also bind.
I know instead of:
#Html.EditorFor(model => model.WOHdr.Attribute1)
I could do:
#Html.TextBoxFor(model => model.WOHdr.Attribute1, new { id = Model.Id + "_Attribute1" })
But then it won't bind when it passes to the controller.
Thoughts?
Try this
#Html.TextBoxFor(model => model.WOHdr.Attribute1, new { #id = #Model.Id + "_Attribute1" })
Use "#"+dynamic value. Now You will get unique Id's
In EditorFor you can use like this
#Html.EditorFor(model => model.WOHdr.Attribute1, null, "id=" + #Model.Id + "" )
the id will generate like this
id="id_1", id="id_2" and so on..
<input id="Checkbox1_#(test.TestId)" type="checkbox" />
i hope upper code will help you
In MVC3, I've been able to rely on Html.DisplayForModel() to generate display's for my data. Using this method, and various templates, I have a single View for displaying several of my Models. What I'm wondering though, is there a way I can get this to work on Lists for my models?
For example, I have a model called Networks. My view to list out multiple networks looks like this:
#model PagedList<Network>
<div id="networkList">
#Html.Grid(Model).Columns(column => {
column.For(x => Html.ActionLink(x.Id.ToString(), "NetworkDetails", new { id = x.Id })).Named("Network ID");
column.For(x => x.Name);
column.For(x => x.Enabled);
}).Attributes(Style => "text-align: center")
#Html.AjaxPager(Model, new PagerOptions() { PageIndexParameterName="page", ShowDisabledPagerItems = false, AlwaysShowFirstLastPageNumber=true },
new AjaxOptions() { UpdateTargetId = "networkList" })
</div>
I'm wondering if it is possible to use a single template when generating lists for my models. I could rely on attributes to know which properties I would like to generate in my list, ie: [ListItem].
The head scratcher for me is, how can I pass a dynamic model to an extension method? If it's of any help, the Html.Grid extension is from MVCContrib. Has anyone else done something similar? It would be great to rely on a template as it would really chop down on the amount of code.
You can achieve it for EditorFor() using the following (it might be similar with your Grid extension method assuming it can take the template name parameter):
// in the main view
#Html.EditorFor(o => o.InvoiceId, "TemplateName", new { Property = "InvoiceId" })
#Html.EditorFor(o => o.Title, "TemplateName", new { Property = "Title" })
// in the template view
#model object
#{ var property = (string)this.ViewData["Property"]; }
Alternatively you can just pass in the name of the template and use this code in the template
var prefix = ViewData.TemplateInfo.HtmlFieldPrefix;
if (prefix.EndsWith("InvoiceId")) { ... }