Html DropDownListFor asp.net C# - c#

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">

Related

Select the Html.DropdownFor

<div class="input-group" style="margin-bottom:30px;">
<span class="input-group-addon">
Brand
</span>
#Html.DropDownListFor(x => x.BrandMod.Id, c,"- Select Brand - ", new { #class = "form-control" ,id="brandid" })
</div>
"This is My Code for Drop Down and I want to select the selected item. I am trying this"
$("#brandid").change(function (rupp) {
var a = $(this).select("option:selected").val();
});
"I am Unable to Load the Selected item."
This doesn't do what you're thinking:
$(this).select("option:selected").val()
In fact, it's probably either silently failing entirely or producing an error. But no matter. What you're trying to do is get the value from this (which is a <select> in your case). That can be done simply with:
$(this).val()
You don't need Specification for getting value in jquery. You have already change event for this
$("#brandid").change(function (rupp) {
var a = $(this).val();
});
or
var a = $("#brandid").val();

How do you add a placeholder using #Html.NopEditorFor

I am trying to add a placeholder to my text field.
I am fairly new with MVC and only been working on it for the pass month.
My code looks like this:
Branch Hours Description: #Html.NopEditorFor(model => model.Description)
BRHOURID: #Html.NopEditorFor(model => model.BrHourCode)
is it possible to add a place holder for these 2 fields?
You need to add a HTML attribute
Branch Hours Description: #Html.NopEditorFor(model => model.Description, new { #placeholder = "Add Your Placeholder Text Here" } })
and that should do it for you

Knockout doesn't bind selectedValue in a select properly

It seems impossible and I have tried a few different ways to create a select list and bind a value to it.
Firstly, and more desirably, I want to do it with Razor:
#Html.DropDownList("SelectedTemplate", Model.Templates, new { #data_bind = "value: Template()" })
The options are just an array of strings. When I bind with Razor then it's a List of SelectListItem objects with Text and Value equal to the same string.
So it renders like this:
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
When I bind via Knockout then the Templates is an array of strings:
var Templates ='["A", "B", "C"]';
which I generate in the cshtml file:
var Templates ='#Html.Raw(Json.Encode(Model.Templates.Select(x=> x.Value)))';
Both create the same markup in HTML. This renders the select list correctly. Template() prints out the correct value, for example "B". However, the drop down doesn't pick the option that is equal to Template(). I also tried:
<select name="SelectedTemplate" data-bind="value: Template(), options: JSON.parse(Templates)"></select>
Same problem here. And I tried all kinds of variations:
#Html.DropDownListFor(m => m.SelectedTemplate, Model.Templates, new { #class = "form-control layoutTemplateSelector", #data_bind = "value: Template(), options: JSON.parse(Templates)" })
#Html.DropDownListFor(m => m.SelectedTemplate, Model.Templates, new { #class = "form-control layoutTemplateSelector", #data_bind = "value: Template()" })
#Html.DropDownList("SelectedTemplate", Model.Templates, new { #data_bind = "value: Template(), options: JSON.parse(Templates)" })
Ideally, I want to use DropDownListFor because on post back I want m.SelectedTemplate to be processed.
The postback works well so far for DropDownListFor, but on load it doesn't show the data-bind: value:Template(), which definitely contains the correct value.
I also tried your idea to use observable array with no success:
self.SelectedContent({
Template: ko.observable(content.Template()),
TemplateList: ko.observableArray(JSON.parse(Templates))
});
#Html.DropDownListFor(m => m.Form.Template, Model.Templates, new {#data_bind = "value: Template(), options: TemplateList()" })
Any ideas what could be wrong here? I'm using Knockout 2.3 and MC.
UPDATE
I found the error.
The value returned from the database contained a space: "A "
whereas the values binding the to the drop down didn't have that space.
This caused all the errors.
As far as I can see the simplest of implementations works well now:
#Html.DropDownList("SelectedTemplate", Model.Templates, new { #data_bind = "value: Template()" })
Even though it was entirely my mistake, I hope it helps someone in the future. The error wasn't immediately apparent

Add prefix to control id and still have it bind MVC Razor

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

MVC Razor Radio Button

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.

Categories