How does one set the label of a checkbox? I looked at some sites and they are using lambda expressions, but I can't understand them. I am new to asp.net MVC.
#{
bool chkVal = false;
}
<li>#Html.CheckBox("chksumma",chkVal,new {#value = "5"})</li>
<li>#Html.LabelFor(, "");
This is a really good way:
<div class="checkbox">
<label>#Html.CheckBoxFor(x => item.IsSelected) #Html.DisplayNameFor(x => item.IsSelected)</label>
</div>
It's what is recommended by bootstrap 3.
It works in a table.
You can click on the check box OR the label to select the box. (This is an important usability feature.)
The cursor is properly the "hand" instead of the arrow pointer.
EDIT
This is really easy to do in Bootstrap 4.
You just wrap your label and input inside form-check markup:
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="defaultCheck1">
<label class="form-check-label" for="defaultCheck1">Default checkbox</label>
</div>
If you are using a Model you could do:
<li>#Html.CheckBoxFor(f=> f.chksumma)</li>
<li>#Html.LabelFor(f=> f.chksumma)</li>
Then use the attributes TGH pointed out
otherwise if you don't have a model all you can do for labels is:
#Html.Label("LabelText")
which prints a standalone label
or and craft it if you want it to link with the item
<label for="chksumma">LAbelText</label>
If you really don't want to hand craft it you can write your own HTML helper as explained here
http://develoq.net/2011/how-to-create-custom-html-helpers-for-asp-net-mvc-3-and-razor-view-engine/
I'm assuming that you want the label to tick the checkbox when you click on it.
In this case, the for attribute of the HTML <label> field must point to the ID of the relevant input element.
If you're using a model, #Html.CheckBoxFor will generate a checkbox without an ID, so you will need to add an ID to the checkbox, then point your label to the same ID. The easiest way is to replicate the checkbox's name into its ID field using the #Html.NameFor helper method. Here's an example:
#Html.CheckBoxFor(x => x.Active, new {id=Html.NameFor(x => x.Active)})
<label for="#Html.NameFor(x => x.Active)">Active</label>
Generated HTML (without validation attributes):
<input id="[0].Active" name="[0].Active" type="checkbox" value="true" />
<input name="[0].Active" type="hidden" value="false" />
<label for="[0].Active">Active</label>
I worked on something similar and got around it by this snipped code
<div class="row">
<div class="col-xs-3">
<label>
#Html.CheckBoxFor(x => x.AdvanceSearch.IsExactPhrase)
#Html.LabelFor(x => x.AdvanceSearch.IsExactPhrase)
</label>
</div> ...
Hope it helps the others
You shouldn't need the <label> tag at all:
<div class="block mTop20">
#HtmlCheckboxFor(f => f.prop)
#Html.LabelFor(f=>f.prop,"This is the label text")
</div>
Related
Here is a reference Image
For a little bit more context I am operating in a C# ASP.NET MVC environment and I am trying to pass a value to a form via button click. For my other two values that are being assigned on the form I am using #Html.EditorFor() and #Html.RadioButtonFor() for a text box and radio button selection respectively. However since there is no #Html.ButtonFor() I am instead trying to assign the value to the form with #Html.HiddenFor() inside of an onclick. This works in terms of the functionality I want from it, but there is a weird visual issue where the symbols following the onclick are also used in the text displayed on the button, so while the button should display the text:
Save Notification
It actually displays
"> Save Notification
Here is the relevant code (with specifically the button markup at the bottom where the issue is taking place). I feel like I am missing something very obvious here and I am very new to HTML and Kendo so I am really lost as to why this is happening.
<div class="row">
<div class="col-sm-6 ref-bottom-margin">
#Html.EditorFor(model => model.SystemStatus.UniversalNotification.SystemNotification, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-sm-4">
#Html.RadioButtonFor(model => model.SystemStatus.UniversalNotification.BannerSeverity, "Alert")
Alert
#Html.RadioButtonFor(model => model.SystemStatus.UniversalNotification.BannerSeverity, "Warning")
Warning
#Html.RadioButtonFor(model => model.SystemStatus.UniversalNotification.BannerSeverity, "Notification")
Notification
</div>
<div class="col-sm-2">
<button class="btn btn-primary" type="submit" value="Universal" onclick="#Html.HiddenFor(model => model.SystemStatus.UniversalNotification.BannerScope)"> Save Notification </button>
</div>
</div>
#Html.HiddenFor will generate " inside onclick attribute, and causing wrong text display
Rendered source code of the button:
<button class="btn btn-primary" type="submit" value="Universal" onclick="<input id="SystemStatus_UniversalNotification_BannerScope" name="SystemStatus.UniversalNotification.BannerScope" type="hidden" value="" />"> Save Notification </button>
Instead of using #Html.HiddenFor, you can get the value from model using #(Model.fieldname). And maybe you will want to pass the value directly into JavaScript function, like below
onclick="someFunction('#(Model.SystemStatus.UniversalNotification.BannerScope)')"
I am trying to trigger the model validation in Blazor by using EditForm.
For some reason, the oninput event doesn't seem to be called if using the InputText, but it works using a simple input element.
Have I missed something?
Here is an HTML sample:
<EditForm Model="#Model" OnValidSubmit="#OnValidSubmit" id="authorize">
<h1 class="mb-3">
<span class="d-block">Authorize</span>
</h1>
<DataAnnotationsValidator />
<div class="form-group">
<label class="sr-only" for="AuthorizeUsername">Username</label>
<div class="input-group mb-2">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fas fa-user"></i></div>
</div>
<InputText type="text" class="form-control" id="AuthorizeUsername" placeholder="Username" #bind-value="#Model.Username" #bind-value:event="oninput" />
</div>
</div>
<div class="form-group">
<label class="sr-only" for="AuthorizePassword">Password</label>
<div class="input-group mb-2">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fas fa-asterisk"></i></div>
</div>
<InputText type="password" class="form-control" id="AuthorizePassword" placeholder="Password" #bind-value="#Model.Password" #bind-value:event="oninput" />
</div>
</div>
<div class="form-group">
<ValidationSummary />
<button type="submit" class="btn btn-outline-primary"><i class="fas fa-sign-in-alt mr-1"></i> Login</button>
</div>
</EditForm>
If you need this for validation, see the answer for this:
How to make an EditForm Input that binds using oninput rather than onchange
Original Answer
TLDR: Blazor Input components do not support this out of the box. You need to roll your own by extending InputBase, and your Razor markup for your new component will put the input event binding directly on the input element.
It would be nice if this came as an out-of-the-box option, but at least there is a way to do it that isn't terrible. Be aware though that this quickly gets more complicated for more complicated input types. If you want your own InputBase<DateTime> derived class, for example, you need to be prepared to correctly handle DateTime formatting in the binding events.
The markup for your own version of InputText, lets call it MyInputTextCode that extends InputBase<string> would look something exactly like this:
#inherits MyInputTextCode;
<input type="text" id="#Id" class="#Class" #bind-value="CurrentValueAsString" #bind-value:event="oninput" />
where MyInputTextCode is the class name of your implementation of InputBase<string>
The usage would essentially be the same as InputText, but you would instead use the file name (witout the extension) of your .razor markup instead of InputText.
UPDATE 4-30-2020
I no longer recommend deriving from InputBase in your code-behind, instead you can simply #inherits an existing form component class such as InputText and override the markup in your .razor file. If this isn't clear please comment on this answer and I'll elaborate further in this update.
It works on a simple input because you are binding to the html attribute "value".
InputText is a C# class. The property name you need to bind to is Value with a capital V.
Change all #bind-value occurrences to #bind-Value and it should work.
As a workaround, I found that changing from Blazor components such as InputTextArea to plain HTML textarea tag and leveraging the binding on them can fix the problem:
<textarea #bind="#ViewModel.TargetProperty" #bind:event="oninput"/>
or for input tags:
<input type="email" #bind="#ViewModel.Email" #bind:event="oninput"/>
Works in .Net 5 Blazor WASM at least.
I found this answer and a workaround:
https://github.com/dotnet/aspnetcore/issues/12657
Basically #bind-Value:event="oninput" is not supported on <InputText> but you can easily derive a new control from 'InputText' which does update on input.
Quoted from the original github post for reference:
Create MyInputText.razor containing:
#inherits Microsoft.AspNetCore.Components.Forms.InputText
<input #attributes="#AdditionalAttributes" class="#CssClass" #bind="#CurrentValueAsString" #bind:event="oninput" />
Now when you use <MyInputText #bind-Value="#someval" /> it will behave just like InputText except it updates on each keystroke.
A similar technique as Amir Mahdi said in another answer, I just wanted to point out that this is explained on the official docs also now for Aspnetcore 6.0 and 7.0.
https://learn.microsoft.com/en-us/aspnet/core/blazor/forms-and-input-components?view=aspnetcore-6.0
See the heading 'InputText based on the input event'.
Here is how they suggest to use it, I however see the value of also being in charge of which client side event will trigger update (usually it will be 'oninput', but maybe you want to use another client side event?)
Just define a new reusable component like CustomInputText.razor with the following content :
#inherits InputText
<input #attributes="AdditionalAttributes"
class="#CssClass"
#bind="CurrentValueAsString"
#bind:event="#UpdateSourceTrigger" />
#code {
[Parameter]
public string UpdateSourceTrigger { get; set; } = "oninput";
}
To use it inside a razor view just use it like a regular InputText field, the only thing that is adjusted is that it automatically binds to the 'oninput' client side event. You can adjust which event also is bound to do an update. This can both be positive sine you see your changes on key stroke and negative in case updating the backend from the UI is slow, as every keyboard stroke will write data back to the bound property, possibly trigger additional processing too if you have bound it to an 'autosave' feature or similar.
I used the name UpdateSourceTrigger here for the property trigger event - as this reminds me a bit how we adjusted things in WPF when to write back to two way bound fields !
Another workaround for this issue would be to add a handler to #oninput and set the value to the model inside this handler:
<EditForm Model="Input">
<InputText #bind-Value="Input.Text" #oninput="HandleInputTextInput" />
</EditForm>
#{
private InputModel Input { get; } = new();
private void HandleInputTextInput(ChangeEventArgs e)
{
Input.Text = e.Value as string;
}
public class InputModel
{
public string? Text { get; set; }
}
}
This way you don't need to create a new component and can still use <InputText />.
Draw back of course is that this might bloat your code with handlers.
I am using MVC6 and have a checkbox input field in my form, but when the form is submitted the value for the checkbox always gets passed to the ViewModel as false:
Here is how the property is declared in my ViewModel:
[Display(Name = "Include Sales Tax")]
public bool IncludeSalesTax { get; set; }
Here is how the form looks in my MVC6 razor form:
<div class="form-group">
<div class="checkbox">
<label><input asp-for="IncludeSalesTax" type="checkbox" value="">#Html.DisplayNameFor(m => m.IncludeSalesTax)</label>
</div>
</div>
I figured the above would be the best way to follow Twitter Bootstrap standards and use the ASP.NET MVC6 asp-for tag for model binding.
When I submit the form the value for IncludeSalesTax is always false, even when checked. What am I doing wrong?
input type checkbox sends an "on" if it is set. Otherwise it is not sent.
It is important, that you set the value attribute to true. In this case it sends true or nothing, which is perfect to bind to a boolean.
<input type="checkbox" name="yourPropertyName" value="true" checked />
Pinki's answer above is good if the checkbox should default to checked.
If the checkbox should default to unchecked, a little in-line javascript sets the value to true or false upon clicking:
<input name="yourPropertyName" type="checkbox" value="false" onchange="this.value=this.checked">
After letting Visual Studio generate the form based on my ViewModel here is how it does it:
<div class="checkbox">
<input asp-for="isTaxable" />
<label asp-for="isTaxable"></label>
</div>
Additionally, I was missing the closing of my input tag. So it can also be done like this which is the bootstrap preferred way:
<label><input asp-for="isTaxable" type="checkbox" value=""/>#Html.DisplayNameFor(m => m.isTaxable)</label>
The razor view engine normally creates a checkbox and one hidden input using the same name.
You can simply use the html below to ensure you get your desired result:
<div class="form-group">
<div class="checkbox">
<input type="checkbox" value="true" name="IncludeSalesTax" />Include Sales Tax
<input type="hidden" value="false" name="IncludeSalesTax" />
</div>
</div>
Bit of an odd one here:
The following razor syntax renders a nce simple html from with a submit button inside the bottom of it.
When i hit that button i would expect a postback to performed but for reason it dosn't ... any ideas??
Oh by the way this is the entire code for the view ...
#model FLM.PRL.EComms.Models.ReplySMS
#using (Html.BeginForm("Reply", "SMS", FormMethod.Post)) {
<h2>Follow Up</h2>
#Html.ValidationSummary(true)
#Html.HiddenFor(model => Model.From)
#Html.HiddenFor(model => Model.To)
<div class="editor-label">Reply</div>
<div class="editor-field">
#Html.EditorFor(model => Model.Message)
#Html.ValidationMessageFor(model => Model.Message)
</div>
<input type="submit" value="Reply" />
<br />
}
EDIT: Resulting markup generated by this view ...
<form action="/SMS/Reply" method="post">
<h2>Follow Up</h2>
<input data-val="true" data-val-required="The From field is required." id="From" name="From" type="hidden" value="xxxxxxxx" /><input data-val="true" data-val-required="The To field is required." id="To" name="To" type="hidden" value="xxxxxxx" /> <div class="editor-label">Reply</div>
<div class="editor-field">
<textarea class="text-box multi-line" id="Message" name="Message">
</textarea>
<span class="field-validation-valid" data-valmsg-for="Message" data-valmsg-replace="true"></span>
</div>
<input id="submitReply" type="submit" value="Reply" />
<br />
</form>
The only reason for this form not to be submitted are scripts interfering with the process. Maybe the validation scripts.
I noted that the Message field is required. Did you provided a value to this field? Don't you have any validation error message?
In the case validation is fine, I suggest removing selectively all the scripts from the page and see what happens. If removing a script results in your form working, you know it is the source of the problem.
I figured it out ... it's the hidden fields ... they are required but populated by the server during the postback so the auto validation prevents the postback client side before the server is able to populate the fields ...
solution:
Don't add empty required fields to an MVC form or turn off validation (not a good idea)
I use DNN and C#. I've got a form with a lot of input and select HTML tag. At the end of form there is a . When I click on it, the page is reload but when I try catch data of form (with Request.Form['formName'] or Request['form']) I've got only empty field (and if I check the value of IsPostback, it's always false). But in the form tag there is value.
FILE View.ascx
<div class="row">
<div class="col-sm-2"> </div>
<div class="col-sm-4">
<label for="formCodiceCanile">Codice Canile</label>
</div>
<div class="col-sm-4">
<input type="text" name="formCodiceCanile" ID="formCodiceCanile" value="<%=InfoScheda.CodiceCanile %>" />
</div>
<div class="col-sm-2"> </div>
</div>
OTHER FIELD (such as input text, select and radio button)
<input type="submit" name="formRegistraScheda" id="formRegistraScheda" value="Registra scheda" />
I know that I can use (and if I use it, there isn't problem because catch the value in the asp:Textbox it's a joke) but in this case I can't use them.
How can I resolve this problem?
PROBLEM SOLVED: the button doesn't do the POST because I use a field's form in the URL to observe the page status. Now I remove this control and I use the IsPostback native variable of C# and the form work!