I have an asp.net web form application that I am trying to re-write in MVC. I'm stuck on how to handle bool? values. I'll show one example.
Demo.aspx:
<asp:RadioButtonList ID="FLOW_TARGET"
RepeatDirection="Horizontal" SelectedValue=""
OnSelectedIndexChanged="FLOW_TARGET_SelectedIndexChanged"
AutoPostBack="true">
<asp:ListItem Selected="True" Value="0" />
<asp:ListItem Value="1" />
</asp:RadioButtonList>
How can I convert this RadioButtonList asp.net into mvc
you can use ASP.NET Html Helpers, there are three various methods you can use for each of the different helpers supplied for radio buttons.
1 - in the case if you have a model:
#Html.RadioButtonFor(model => model.x, "textHere", new { #checked = true })
then you can add attributes after checked=true to handle all bool values
2 - if you want to make a simple Radio :
#Html.RadioButton("nameHere", "valueHere", new { id = "yourId" })
3- to make a list of Radios:
You can start by using the foreach like this:
foreach (var x in Model.y)
{
#Html.RadioButtonFor(m => m.something, x.Id) #x.Name
}
so you can always ovverid the RadioButtonFor or RadioButton with all you attributes and their values using this way,
i hope my answer is the right one for your case
Related
Hi I need some help as I am new to MVC. I have a Drop Down List that is being populated with values from the config. I am going to use this drop down to pass a value when hitting submit to run a Query and bring back data into a table.
Where I need help:
If a user wants to reset the drop down back to "Choose Your Value" and clear the table of the data for in prep to run a new query, I want them to be able to click the "Clear" button and be able to do so.
I searched a lot and learned a lot about JavaScript ways of doing this, but I would like to use .NET and MVC.
Here is my Drop Down code:
#{
ViewBag.Title = "Index";
}
#Html.DropDownList("YourElementName",
(IEnumerable<SelectListItem>)ViewBag.DropdownVals, "--Choose Your Value--",
new {
//size = "5",
style = "width: 600px"
}
I have a button like this:
<input id="Button2" type="button" value="Clear" />
Can the button call some code in the controller that will clear both the list and table data?
Please explain in detail if you have time.
Any help is much appreciated.
Controller as it is right now:
public ActionResult Index()
{
//ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
string[] values = (ConfigurationManager.AppSettings["DropdownValues"]).Split(',').Select(sValue => sValue.Trim()).ToArray();
List<SelectListItem> dropDowns = new List<SelectListItem>();
for (int i = 0; i < values.Length; i++)
{
dropDowns.Add(new SelectListItem { Text = values[i], Value = values[i] });
}
ViewBag.DropdownVals = dropDowns;
return View();
}
You can simply reload the page, which will set the dropdown and the page to default.
<input id="Button2" type="button" value="Clear" onclick="window.location.reload()" />
Again, this also depends on how you are fetching the data. If it is a Get request with dropdown value in the query string, then this wouldn't work.
You'd have to do:
<input id="Button2" type="button" value="Clear" onclick="location.href='#Url.Action("Index", "ControllerName")'" />
The natural way to do something like that is using client side code, you don't need something in the server to do this.
Using server side code, is an overkill, but the simple way is to reload the same page (where the dropdownlist is set by default without a selected item).
For a simple javascript way, and not reloading the page:
<input id="Button2" type="button" value="Clear" onclick="document.getElementById('YourElementID').value=''" />
I am trying to generate a unique label and and input text box for a partial view that is being used to render a list of user input rows.
By unique I mean that each input text box should have its unique html "id" and "name" so that when is submitted each input can be identified
In the View I have
#model UserDataModel
#{
var inpName = "benefName" + #Model.Row;
var inpAge = "benefAge" + #Model.Row;
}
#Html.LabelFor(x => x.Name, new { #class="labelhalf"})
#Html.EditorFor(x => x.Name, new { id = #inpName, htmlAttributes = new { #class = "form-control animated" } })
When the view is being render this is what I am seeing
<label class="labelhalf" for="Name">Nombre (Opcional)</label>
<input class="text-box single-line" id="Name" name="Name" type="text" value="">
As you can see the "name" and "id" attributes of the text input is "Name" and "Name" and is not using the value of the #inpName variable ("benefName1" for example)
Also I am trying to assign some CSS classes to that same input using "htmlAttributes"
I had previously tried this with this approach
<label form="FormStep_01" for=#inpName class="labelhalf">Nombre (Opcional)</label>
<input form="FormStep_01" id=#inpName class="form-control animated" pattern="^[_A-z0-9]{1,}$" type="text" placeholder="" required="">
...but the content of the input fields with this approach are not being submited and that is the reason I am trying to use the #Html.EditorFor
UPDATE
I am now using the TextBoxFor which takes the "id" and the "class" fine but not the "name" which is used in the submit
#Html.LabelFor(x => x.Name, new { #class = "labelhalf" })
#Html.TextBoxFor(x => x.Name, new { #id = #inpName, name = #inpName, #class = "form-control animated" })
Please let me know how to achieve this in MVC4
Issue 1 (Using EditorFor())
You cannot add html attributes using EditorFor() in MVC-4. This feature was not introduced until MVC-5.1, and then the correct usage is
#Html.EditorFor(m => m.SomeProperty, new { htmlAttributes = new { someAttribute = "someValue" }, })
Issue 2 (Using TextBoxFor())
You cannot change the value of the name attribute using new { name = "someValue" }. The MVC team built in a safe guard to prevent this because the whole purpose of using the HtmlHelper methods to generate form controls is to bind to your model properties, and doing this would cause binding to fail. While there is a workaround, if you do discover it, don't do it! As a side note - the following line of the private static MvcHtmlString InputHelper() method in the source code
tagBuilder.MergeAttribute("name", fullName, true);
is what prevents you overriding it.
Issue 3 (Manual html)
You not giving the inputs a name attribute. A form posts back a name/value pair based on the name and value attributes of successful controls, so if there is no name attribute, nothing will be sent to the controller.
Side note: If your manually generating html, there is no real need to add an id attribute unless your referring to that element in javascript or css.
Its unclear why your trying to create a input for something that does not appear to relate to your model, but if your trying to dynamically generate items for adding items to a collection property in your model, refer the answers here and here for some options which will allow you to bind to your model.
I have a dx:ASPxGridView (Dev express gridview) which contains HTML checkboxes - input type="checkbox" control.
Problem is how can i access these HTML checkboxes at server side, so that i can check those checkboxes according to condition.
Please suggest me how can i access these HTML checkboxes on server side.
Code image can be found here
Thanks
Girish Rawat
First, to access a HTML element on a server, you need to mark it with the runat="server" attribute.
To access your checkbox, handle the ASPxGridView.HtmlDataCellPrepared event. In the event handler, you can get your input by using the ASPxGridView.FindRowCellTemplateControl method. You will also need to set ID for the input.
<dx:ASPxGridView ID="ASPxGridView1" runat="server" AutoGenerateColumns="False" OnDataBinding="ASPxGridView1_DataBinding" OnHtmlDataCellPrepared="ASPxGridView1_HtmlDataCellPrepared" KeyFieldName="ID">
<Columns>
<dx:GridViewDataCheckColumn VisibleIndex="0">
<DataItemTemplate>
<input id="check" type="checkbox" runat="server" />
</DataItemTemplate>
</dx:GridViewDataCheckColumn>
</Columns>
<Styles AdaptiveDetailButtonWidth="22"></Styles>
</dx:ASPxGridView>
protected void ASPxGridView1_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e) {
HtmlInputCheckBox check = (HtmlInputCheckBox)ASPxGridView1.FindRowCellTemplateControl(e.VisibleIndex, e.DataColumn, "check");
check.Checked = GetValue((int)e.KeyValue);
}
public bool GetValue(int id) {
// your logic
return id % 2 == 0;
}
I am having a partial view which has textbox, drop-down-list and readio buttons. I have to load this partial view on a view in a for loop. textbox and drop-down controls in the partial view are getting populated properly but radio-buttons are not. When the last time the partial view loads in the for loop radio-buttons are also populated properly (as desired) from the model that I am passing to the partial view. My partial view calling code is as below:
#Html.Partial("~/Views/Shared/_PDFReportPartialView.cshtml", item)
here "item" is the model. and my radio-buttons are given below (From the partial view...)
<div class="editor-field">
#Html.RadioButton("Job_Type", true, new { style = "width:15px; background-color:Window;", #class = "radiobuttonlist", #id = "Job_Type_" + #Model.ReportID, #name = "Job_Type_" + #Model.ReportID }) Support
#Html.RadioButton("Job_Type", false, new { style = "width:15px; background-color:Window;", #class = "radiobuttonlist", #id = "Job_Type_" + #Model.ReportID, #name = "Job_Type_" + #Model.ReportID }) Installation
#Html.ValidationMessageFor(model => model.Job_Type)
</div>
When I see the view source I see that radio-buttons are checked properly as below:
<input checked="checked" class="radiobuttonlist" id="Job_Type_66" name="Job_Type" style="width:15px; background-color:Window;" type="radio" value="False" />
Can anybody help me here?
It seems that the default ASP.NET MVC2 Html helper generates duplicate HTML IDs when using code like this (EditorTemplates/UserType.ascx):
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<UserType>" %>
<%: Html.RadioButton("", UserType.Primary, Model == UserType.Primary) %>
<%: Html.RadioButton("", UserType.Standard, Model == UserType.Standard) %>
<%: Html.RadioButton("", UserType.ReadOnly, Model == UserType.ReadOnly) %>
The HTML it produces is:
<input checked="checked" id="UserType" name="UserType" type="radio" value="Primary" />
<input id="UserType" name="UserType" type="radio" value="Standard" />
<input id="UserType" name="UserType" type="radio" value="ReadOnly" />
That clearly shows a problem. So I must be misusing the Helper or something.
I can manually specify the id as html attribute but then I cannot guarantee it will be unique.
So the question is how to make sure that the IDs generated by RadioButton helper are unique for each value and still preserve the conventions for generating those IDs (so nested models are respected? (Preferably not generating IDs manually.)
In addition to PanJanek's answer:
If you don't really need the elements to have an id, you can also specify id="" in the htmlAttributes (i.e. new { id="" }) parameter of helpers. This will result in the id attribute being left out completely in the generated html.
source: https://stackoverflow.com/a/2398670/210336
I faced the same problem. Specyfying IDs manually seems to be the only solution. If you don't need the ids for anything (like javascript), but want it only to be unique you could generate Guids for them:
<%: Html.RadioButton("", UserType.Primary, Model == UserType.Primary, new { id="radio" + Guid.NewGuid().ToString()}) %>
A more elegant solution would be to create your own extension method on HtmlHelper to separate ID creation logic from the view. Something like:
public static class HtmlHelperExtensions
{
public static MvcHtmlString MyRadioButtonFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, bool value)
{
string myId = // generate id...
return htmlHelper.RadioButtonFor(expression, value, new {id=myId});
}
}
The helper method could use ViewContext and Model data to create more meaningfull IDs.
UPDATE:
If you use EditorTemplates to render the control like this
<%= Html.EditorFor(m=>m.User, "MyUserControl") %>
Then inside the MyUserControl.ascx (placed in ~/Views/Shared/EditorTemplates) you can use ViewData.TemplateInfo.HtmlFieldPrefix property to access the parent control ID or Html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId("MyPostfixPart") to generate prefixed id. Theese methods could be used in the helper extension above.
The same works with controls rendered with Html.Editor(...) and Html.EditorForModel(...). In the Html.Editor helper you can also specify htmlFiledName manually if you want.
When you embed the control with
<%= Html.Partial("UserControl", Model.User) %>
generation of meaningfull IDs is harder because the Html.Partial will not provide information about the prefix - the ViewData.TemplateInfo.HtmlFieldPrefix will be always empty. Then, the only solution would be to pass the prefix manually to the ascx control in as ViewData key of as a model field which is not as elegant a solution as the previous one.
If you do need to access the radio buttons via jQuery, I find that often the better place to set the id's will be on the page, close to their intended usage. This is how I did the same:
#Html.Label(Resource.Question)
#Html.RadioButtonFor(m => m.Question, true, new {id = "QuestionYes"}) Yes
#Html.RadioButtonFor(m => m.Question, false, new {id = "QuestionNo"}) No
Then my jQuery:
if ($("input[id='QuestionNo']").is(":checked")) {
$('#YesOptionalBlock').removeClass('showDiv');
$('#YesOptionalBlock').addClass('hideDiv');
}