How do I configure Checkboxes in Asp.Net MVC Razor.
Since in the documentation we have the following configuration Materialize for checkboxes :
<p>
<label>
<input type = "checkbox" />
<span> Network </span>
</label>
</p>
And in Razor I could not perform this configuration.
<div class = "input-field col s12">
#Html.EditorFor (model => model.AnnualDestaque)
#Html.LabelFor (model => model.AnnualDestaque)
#Html.ValidationMessageFor (model => model.AnnualDestaque, "", new {#class = "text-danger"})
</div>
Please include model Name in your cshtml page
#model WebApplication3.Models.Test
#{
ViewBag.Title = "Home Page";
}
#using (Html.BeginForm("Save", "Home", FormMethod.Post))
{
<div class="row">
<div class="col-md-4">
#Html.TextBoxFor(m => m.EmployeeName)
#Html.CheckBoxFor(m=>m.IsSelected)
</div>
<input type="submit" value="Save" />
</div>
}
Model
public class Test
{
public string EmployeeName { get; set; }
public bool IsSelected { get; set; }
}
If you just want to have a checkbox binded with your model like that :
public class Network
{
public bool Selected { get; set; }
public string Name { get; set; }
}
Just use :
#Html.CheckBoxFor(m=>m.Selected)
#Html.LabelFor(m=>m.Name)
I was able to solve it, and I am passing the answer.
I used Html Helper Documentation Html Helper MVC
It worked perfectly without mistakes the way it's meant to be.
<div class="input-field col s12">
<label>
<input data-val="true"
data-val-required="The Advertisement field is required."
id="Advertisement"/**** m => m.Advertisement ****/
name="Advertisement"/**** m => m.Advertisement ****/
type="checkbox"
value="true" />
<span>Anuncio Destaque</span>
<input name="Advertisement" type="hidden" value="false" />
</label>
</div>
You can make it work doing this:
<label>
<input type="checkbox" name="FIELDNAME" id="FIELDNAME" value="true" class="filled-in" #(Model.FIELDNAME? "checked" : "") />
<span>#Html.DisplayNameFor(model => model.FIELDNAME)</span>
</label>
<input name="FIELDNAME" type="hidden" value="false" />
Related
I am new to kendo UI. Trying to validate my form using custom rules with kendo-rules attributes. I am referring to this link https://demos.telerik.com/aspnet-core/validator . The custom rules are working but somehow the validation message is getting triggered on different controls.
I am trying to set the custom rule on my "FirstName" field. If "FirstName" field has value less than 5 characters then, validation message "First name cannot be less than 5 characters" should come, for "FirstName" field.
However, I am getting the validation messages on different controls. Refer to the snapshot below.
The expected behaviour is , first required field error should come and then if the user enters first name value less than 5 characters then this "First name cannot be less than 5 characters" error should come.
Here is my code:
Create.cshtml
#model KendoFormValidation_Demo.Models.Person
#{
ViewData["Title"] = "Create";
}
#{
var messages = new Dictionary<string, string>() { { "custom", "First name cannot be less than 5 characters" } };
var rules = new Dictionary<string, string>() { { "custom", "customFunction" } };
}
<div class="row">
<div class="col-md-4">
<form id="PersonForm" kendo-validator="true" kendo-messages="messages" kendo-rules="rules">
<div class="form-group">
<label asp-for="FirstName"></label>
<input asp-for="FirstName" class="form-control" />
<span class="text-danger k-invalid-msg" data-for="FirstName"></span>
</div>
<div class="form-group">
<label asp-for="LastName"></label>
<input asp-for="LastName" class="form-control" />
<span asp-validation-for="LastName" class="text-danger k-invalid-msg" data-for="LastName"></span>
</div>
<div class="form-group">
<label asp-for="Age"></label>
<input class="form-control" for="Age" />
<span asp-validation-for="Age" class="text-danger k-invalid-msg" data-for="Age"></span>
</div>
<div class="form-group">
<label asp-for="Address"></label>
<input asp-for="Address" class="form-control" />
<span asp-validation-for="Address" class="text-danger k-invalid-msg" data-for="Address"></span>
</div>
<div class="form-group">
<label asp-for="Email"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger k-invalid-msg" data-for="Email"></span>
</div>
<div class="form-group">
<label asp-for="Phone"></label>
<input asp-for="Phone" class="form-control" />
<span asp-validation-for="Phone" class="text-danger k-invalid-msg" data-for="Phone"></span>
</div>
<div class="form-group">
<label asp-for="Dob"></label>
<input asp-for="Dob" class="form-control kendo-date-picker" />
<span asp-validation-for="Dob" class="text-danger k-invalid-msg" data-for="Dob"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="k-button k-button-md k-rounded-md k-button-solid-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index" class="k-button k-button-md k-rounded-md k-button-solid">Back to List</a>
</div>
<script>
function customFunction(input) {
debugger;
return input.attr('name') === "FirstName" && input.length<5;
}
$(document).ready( function () {
$(".kendo-date-picker").each(function(){
$(this).kendoDatePicker({
format: "MM/dd/yyyy",
dateInput: true,
value: $(this).val()
}).data('kendoDatePicker')._dateInput.setOptions({
messages:{
"year": "yyyy",
"month": "mm",
"day": "dd"
}
});
});
var validator = $("#PersonForm").data("kendoValidator");
$("form").submit(function(event) {
event.preventDefault();
if (validator.validate()) {
alert("Success");
} else {
alert("fail");
}
});
});
</script>
Person.cs
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Address { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
[DataType(DataType.Date)]
public DateTime Dob { get; set; }
}
I am using .Net 6 and Telerik version: ASP.NET Core R2 2022 SP1
Can anybody help me on this? Did I miss anything here.
Thank You
I have a view model with the following properties:
// I set the values from the database
public List<Document> AvailableDocuments { get; set; }
// I need to set the values from a front end <form>
public List<RequiredDocument> RequiredDocuments { get; set; }
The RequiredDocument model contains the following properties:
// This should be an Id, maybe a hidden input
public Document Document { get; set; }
// This should be a number input
public int RequiredCopies { get; set; }
// This should be a checkbox
public bool IsRequired { get; set; }
In my view I'm looping through AvailableDocuments and every iteration should bind to a RequiredDocument model (where the user may set the values for the RequiredCopies number).
The form is submitted via Ajax. How can I bind the form to RequiredDocuments?
#foreach (Document doc in Model.AvailableDocuments)
{
<div class="reqdoc">
<!-- RequiredDocument.Document -->
<input type="hidden" name="Document" value="#doc.Id" />
<div class="form-check">
<!-- RequiredDocument.IsRequired -->
<input class="form-check-input" type="checkbox" value="" />
<label class="form-check-label">
#doc.Name
</label>
</div>
<!-- RequiredDocument.RequiredCopies -->
<input class="form-control" type="number" />
</div>
}
You can use this kind of for loop I am doing similar in my projects & it works
<table>
#for (int i = 0; i < (int)ViewBag.Count; i++)
{
#Html.HiddenFor(model => model.AvailableDocuments.ToList()[i].ID)
<tr>
<td>
#Html.CheckBoxFor(model => model.RequiredDocuments.ToList()[i].IsRequired, new { id = "chk_" + i, #class = "custom-checkbox" })
</td>
<td>
#Html.DisplayFor(model => model.AvailableDocuments.ToList()[i].Name)
</td>
<td>
#Html.TextBoxFor(model => model.RequiredDocument.ToList()[i].RequiredCopies, new { id = "RequiredCopies" + i, #class = "form-control" })
</td>
</tr>
}
</table>
Just pass a ViewBag.Count from Your get method.
Work with index and modify the name attribute as:
#{
int i = 0;
foreach (Document doc in Model.AvailableDocuments)
{
<div class="reqdoc">
<!-- RequiredDocument.Document -->
<input type="hidden" name="RequiredDocuments[#i].Document.Id" value="#doc.Id" />
<div class="form-check">
<!-- RequiredDocument.IsRequired -->
<input class="form-check-input" type="checkbox" value="" name="RequiredDocuments[#i].IsRequired" />
<label class="form-check-label">
#doc.Name
</label>
</div>
<!-- RequiredDocument.RequiredCopies -->
<input class="form-control" type="number" name="RequiredDocuments[#i].RequiredCopies" />
</div>
i++;
}
}
I have a model (simplified, removing extraneous properties):
public class SubmitModel
{
[Required]
[DataType("FileUpload")]
[Display(Name = "Formatted Data File")]
public HttpPostedFileBase FormattedDataFile { get; set; }
}
A controller:
[HttpPost]
public ActionResult Submit(SubmitModel model)
{
if (this.ModelState.IsValid)
{
//...
}
return this.View(model);
}
A FileUpload view:
#{
IDictionary<string, object> htmlAttributes = Html.GetUnobtrusiveValidationAttributes(string.Empty);
}
<input type="file" id="#this.ViewData.TemplateInfo.GetFullHtmlFieldId(string.Empty)" name="#this.ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty)" #(new MvcHtmlString(htmlAttributes.ToHtmlAttributesString())) />
#Html.ValidationMessage(string.Empty)
And a simple view:
#model SubmitModel
#using (Html.BeginForm())
{
<div class="Form">
#Html.EditorForModel()
<div class="Footer">
<button class="Button" data-options='{ "icons": { "primary": "ui-icon-disk" } }'>Submit</button>
</div>
</div>
}
Which renders to this HTML:
<form action="/Data/Submit" method="post">
<div class="Form">
<div class="Item">
<div class="Label Required">Formatted Data File:</div>
<div class="Input">
<input type="file" id="FormattedDataFile" name="FormattedDataFile" data-val-required="The Formatted Data File field is required." data-val="true" />
<span class="field-validation-error" data-valmsg-for="FormattedDataFile" data-valmsg-replace="true">The value 'Test.xlsx' is invalid.</span>
</div>
</div>
<div class="Footer">
<button class="Button" data-options='{ "icons": { "primary": "ui-icon-disk" } }'>Submit</button>
</div>
</div>
</form>
Upon clicking Submit, I'm brought to the proper controller/action and my model's FormattedDataFile property is null. The ModelState is invalid, saying that "The Formatted Data File field is required." This same code worked fine in some MVC-3 projects I've done - is there anything different regarding this in MVC-4?
i think you are missing enctype="multipart/form-data" in the form
http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2
I have a view model with a from that includes a set of checkboxes. I need the check boxes to map to an array when binding in the post back method of my controller.
Here's the view model.
#model TMDM.Models.TestSeriesCreateViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create a Test Series</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
#Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Title)
#Html.ValidationMessageFor(model => model.Title)
</div>
<h3>Which Test Collections are in this Test Series?</h3>
<div class="editor-field">
#{
var i = 0;
foreach (var testCollection in Model.TestCollections)
{
<input type="checkbox" id="ChosenTestCollectionIds[#i]" name="ChosenTestCollectionIds[#i]" value="#testCollection.Id" />
<span>#testCollection.Title</span>
<br />
i++;
}
}
</div>
<p>
<input type="submit" value="Save" class="medium green awesome" />
#Html.ActionLink("Cancel", "Index", "TestSeries", null, new { #class = "medium black awesome" })
</p>
</fieldset>
The form is rendering fine, I've checked the source and each output check box has a different number for their id and name fields.
<input type="checkbox" id="ChosenTestCollectionIds[0]" name="ChosenTestCollectionIds[0]" value="5" />
<input type="checkbox" id="ChosenTestCollectionIds[1]" name="ChosenTestCollectionIds[1]" value="6" />
//etc...
Here is the view model.
public class TestSeriesModel
{
public int Id { get; set; }
public string Title { get; set; }
}
public class TestSeriesCreateViewModel : TestSeriesModel
{
public List<ITestCollectionDataObject> TestCollections { get; set; }
public int[] ChosenTestCollectionIds { get; set; }
}
Problem I'm having is that when the form posts back the ChosenTestCollectionIds array comes back null. What am I doing wrong here?
ANSWER
I've worked out how to do it:
<input type="checkbox" id="[#i]" name="ChosenTestCollectionIds" value="#testCollection.Id" />
<input type="checkbox" id="[#i]" name="ChosenTestCollectionIds" value="#testCollection.Id" />
I always come back to Phil Haack's post about model binding a list. In addition, I always define my own index because my user's will alter the list on the client side then post back the changes.
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
Set the name of the input types to all be the same. You can also create a custom model binder if you are trying to bind a more complex model than just a list. Here is an excellent article on the different ways to bind to your models
Various Model Binding techniques
The model binding just isn't working for me - I always get NULL coming through to the controller! Any thoughts people?
Rob
Here is my action signature:
public ActionResult SearchForUser(SearchForUserModel m)
Here is my Razor header model declaration:
#model WebOne.Models.StatusIndexModel
StatusIndexModel is a composite model containing SearchForUserModel:
public class SearchForUserModel
{
[Required(ErrorMessage = "Search information required")]
[DisplayName("Contact Search")]
public string Search { get; set; }
}
Here is my Razor:
#using (Html.BeginForm("SearchForUser", "Status"))
{
<div>
<div class="editor-field">
#Html.TextBoxFor(m => m.searchForUserModel.Search)
<input type="submit" class="formbutton_small" value="Find" />
<br />
#Html.ValidationMessageFor(m => m.searchForUserModel.Search)
</div>
</div>
}
Here is the generated HTML:
<form action="/Status/SearchForUser" method="post">
<div>
<div class="editor-field">
<input data-val="true" data-val-required="Search information required" id="searchForUserModel_Search" name="searchForUserModel.Search" type="text" value="" />
<input type="submit" class="formbutton_small" value="Find" />
<br />
<span class="field-validation-valid" data-valmsg-for="searchForUserModel.Search" data-valmsg-replace="true"></span>
</div>
</div>
</form>
You need to specify the prefix:
public ActionResult SearchForUser(
[Bind(Prefix="searchForUserModel")]SearchForUserModel m
)