Bootstrap "required" class not working for current MVC web app - css

I'm currently working with an MVC web app. I went in to restyle the Create template and after doing so, I lost the ability to mark required fields with a red asterisk. I don't understand why my code is no longer working. Please help. Code below:
HTML/Razor Syntax
<div class="form-group required col-md-4">
#Html.LabelFor(model => model.Buy1FirstName)
#Html.EditorFor(model => model.Buy1FirstName, new { htmlAttributes = new { #class = "form-control", required = "required" } })
#Html.ValidationMessageFor(model => model.Buy1FirstName, "Please enter a valid first name", new { #class = "text-danger" })
</div>
My CSS/StyleSheet
.form-group .required .control-label:after {
content:" *" !important;
color:red !important;
}
This is what it currently looks like. It should have a red * after the label "First Name".

I believe that there are two small errors here.
The control-label class reference is in your css, but not in the actual html tag.
The css selectors are a little off just as the comments mention. I just tried your code and was able to see the red asterisk with
these changes:
<div class="form-group required col-md-4">
#Html.LabelFor(model => model.Buy1FirstName, new { #class = "control-label" })
#Html.EditorFor(model => model.Buy1FirstName, new { htmlAttributes = new { #class = "form-control", required = "required" } })
#Html.ValidationMessageFor(model => model.Buy1FirstName, "Please enter a valid first name", new { #class = "text-danger" })
.form-group.required .control-label:after {
content: " *" !important;
color: red !important;
}
Notice the only thing I changed was adding the class reference in the html label to "control-label", and removing the space between .form-group and .required in the css section.

Related

ASP.NET MVC Dropdown Default value

Please look at my code. I am trying to load the default value for the drop-down. value is not accepting from the design. I'm loading data to the combobox from, the account controller, I have added list of items to the Tempdata and then in the design I'm assigning the list to the combo box. So here when loading the form I need to set the default value for the combo box drop down list. Please help
This is how I assigning values from the account controller.
List<Request_Types> RequestTyleList = db.Request_Types.Where(r => r.Status == true).ToList();
List<SelectListItem> ReqTypeDropDown = RequestTyleList.Select(r => new SelectListItem { Text = r.Request_Type, Value = r.Id.ToString() }).ToList();
TempData["RequestTyleList"] = ReqTypeDropDown;
This how I called that TempData in the view:
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
List<SelectListItem> ReqTypes = (List<SelectListItem>)TempData.Peek("RequestTyleList");
}
And this is where I assigning that values to the Combobox in the view
<div class="col-md-6 col-sm-6">
<div class="form-group row">
#Html.LabelFor(model => model.ReqType, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.DropDownListFor(model => model.ReqType, ReqTypes, new { #class = "js-dropdown" })
#Html.ValidationMessageFor(model => model.ReqType, "", new { #class = "text-danger" })
</div>
</div>
</div>
So I when opening the view, I need to assign the default value to the ReqTypes
Just add the following parameter to assign default value
#Html.DropDownListFor(model => model.ReqType, new SelectList(ReqTypes,"Value","Text","Your_Default_Value"), "Select",new { #class = "js-dropdown" })

Required Validation Not working For DropdownList in MVC

Below View Code. when i click on Create button without Selecting Activity. it is not showing validation message. i am using Required attribute in Model Class
<div class="form-group">
#Html.LabelFor(model => model.TransactionTypeID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.TransactionTypeID, new SelectList(ViewBag.GetT, "TransactionTypeID", "TransactionType"), "--Select--", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TransactionTypeID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ActivityID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ActivityID, new SelectList(ViewBag.GetA, "ActivityID", "ActivityName"), "--Select--", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ActivityID, "", new { #class = "text-danger" })
</div>
</div>
//Controller code
public ActionResult Create()
{
List<TransactionTypeMaster> T = new DATransactionTypeMaster().GetListAll();
ViewBag.GetT = T;
List<ActivityMaster> A = new DAActivityMaster().GetListAll();
ViewBag.GetA = A;
return View();
}
Can Any One Help on this. Need To Know Where i m going Wrong
when i click on Create button without Selecting Activity. it is not showing validation message. i am using Required attribute in Model Class
try giving the default '--Select--' options in your drop downs a value of 0.
In your model, make sure your drop down value is set to '[Required]' and also give it the attribute:
[Range(1, Int32.MaxValue, ErrorMessage = "Must Select A Value")]
basically letting it only accept values > 0
I think you TransactionTypeID is int, make that Nullable that would fix this issue. Currently it doesn't work because by default it might be sending zero as a value by using null, it would send null when user doesn't touch this field.

Kendo Editors not working in jQuery Steps?

I am using jQuery steps within a form.
I have some model properties which I want to edit using Kendo Editors.
I a using following (partial) code, the rest is markup for the jQuery wizard:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Start, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Start, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Start, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.End, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.End, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.End, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#(Html.Kendo().DropDownListFor(x => x.RecurrenceRule)
.Name("recurrenceRule")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(new List<SelectListItem>
{
new SelectListItem
{
Text = #"Nie",
Value = "Never"
},
new SelectListItem
{
Text = #"Täglich",
Value ="Daily"
},
new SelectListItem
{
Text = #"Monatlich",
Value ="monthly"
}
}))
</div>
</div>
}
For some reason, the editors for Date properties are not properly displayed while the #(Html.Kendo().DropDownListFor( is working just fine.
In another step (not documented here) #(Html.Kendo().MultiselectFor( does not work correctly either.
What could cause this issue?
Update:
Positioning this code outside the markup for jQuery steps works fine. Here is my code for the wizard:
#using (Ajax.BeginForm("Wizard_Submit", "Wizard", new
{
Area = ""
}, new AjaxOptions
{
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace
}, new
{
id = "wizardSumbit"
}))
{
////0
<div id="wizard">
<h3></h3>
<section>
<p></p>
#(Html.Kendo().DropDownListFor(x => x.SlRateBaseTypes)
.Name("slRateBaseTypes")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(new List<SelectListItem>
{
new SelectListItem
{
Text = #"abc",
Value = ((int) SlRateBaseTypes.Course).ToString()
},
new SelectListItem
{
Text = #"cde",
Value = ((int) SlRateBaseTypes.Leisure).ToString()
}
}))
</section>
#*//1*#
<h3>Vorlage</h3>
<section>
<p>Wähle eine Vorlage aus</p>
#(Html.Kendo().DropDownListFor(x => x.OfferingTemplateId)
.Name("offeringTemplate")
.DataTextField("Text")
.DataValueField("Value")
.Events(x => x.Change("onOfferingTemplateChange"))
.DataSource(
source => source
.Read(read => read.Url(Url.Action("Wizard_GetOfferingTemplates", "Wizard")).Data("getSlRateBaseTypesSelection").Type(HttpVerbs.Post))
.ServerFiltering(true)
)
.AutoBind(false))
<div id="offeringTemplateDescription"></div>
</section>
#*//2*#
<h3></h3>
<section>
<p></p>
<label for="optional"></label>
#(Html.Kendo().MultiSelectFor(x => x.SlRateBaseTypes)
.Name("selectOfferingRateTypes")
.Placeholder("")
.AutoClose(false)
.DataTextField("Text")
.DataValueField("Value")
.DataSource(
source => source
.Read(read => read.Url(Url.Action("Wizard_GetPossibleOfferingRates", "Wizard")).Data("getSlRateBaseTypesSelection").Type(HttpVerbs.Post))
.ServerFiltering(true)
)
)
..
}
Developer options reveal following :
"Cannot read property 'inspectKendoWidget' of undefined"
"TypeError: Cannot read property 'inspectKendoWidget' of undefined
at :1:15"
Update 2:
this is the html code for the documented datepicker:
<span class="k-widget k-datetimepicker k-header k-input" style="width: 100%;">
<span class="k-picker-wrap k-state-default"><input data-val="true" data-val-date="The field Start must be a date." data-val-required="The Start field is required." id="Start" name="Start" type="text" value="01.01.0001 00:00" data-role="datetimepicker" class="k-input" role="combobox" aria-expanded="false" aria-disabled="false" style="width: 100%;" vk_15f93="subscribed">
<span unselectable="on" class="k-select">
<span class="k-link k-link-date" aria-label="Open the date view">
<span unselectable="on" class="k-icon k-i-calendar" aria-controls="Start_dateview"><
/span>
</span>
<span class="k-link k-link-time" aria-label="Open the time view">
<span unselectable="on" class="k-icon k-i-clock" aria-controls="Start_timeview">
</span>
</span>
</span>
</span>
</span>
Just in case anybody cares:
you'll have to remove some css styles in the jQuery steps css file
-> change to:
.tabcontrol ul > li
{
display: block;
/*padding: 0;*/
}
Update:
Also important: Actually the basic problem was solved by modifiying the jquery.steps.js file according to another post I found on the internet:
--> comment this section
//function render(wizard, options, state)
//{
// // Create a content wrapper and copy HTML from the intial wizard structure
// var wrapperTemplate = "<{0} class=\"{1}\">{2}</{0}>",
// orientation = getValidEnumValue(stepsOrientation, options.stepsOrientation),
// verticalCssClass = (orientation === stepsOrientation.vertical) ? " vertical" : "",
// contentWrapper = $(wrapperTemplate.format(options.contentContainerTag, "content " + options.clearFixCssClass, wizard.html())),
// stepsWrapper = $(wrapperTemplate.format(options.stepsContainerTag, "steps " + options.clearFixCssClass, "<ul role=\"tablist\"></ul>")),
// stepTitles = contentWrapper.children(options.headerTag),
// stepContents = contentWrapper.children(options.bodyTag);
// // Transform the wizard wrapper and remove the inner HTML
// wizard.attr("role", "application").empty().append(stepsWrapper).append(contentWrapper)
// .addClass(options.cssClass + " " + options.clearFixCssClass + verticalCssClass);
// // Add WIA-ARIA support
// stepContents.each(function (index)
// {
// renderBody(wizard, state, $(this), index);
// });
// stepTitles.each(function (index)
// {
// renderTitle(wizard, options, state, $(this), index);
// });
// refreshStepNavigation(wizard, options, state);
// renderPagination(wizard, options, state);
// }
-->replace with this
function render(wizard, options, state) {
// Create a content wrapper and copy HTML from the intial wizard structure
var contentWrapperTemplate = "<{0} class=\"{1}\"></{0}>",
stepsWrapperTemplate = "<{0} class=\"{1}\">{2}</{0}>",
orientation = getValidEnumValue(stepsOrientation, options.stepsOrientation),
verticalCssClass = (orientation === stepsOrientation.vertical) ? " vertical" : "",
contentWrapper = $(contentWrapperTemplate.format(options.contentContainerTag, "content " + options.clearFixCssClass)),
stepsWrapper = $(stepsWrapperTemplate.format(options.stepsContainerTag, "steps " + options.clearFixCssClass, "<ul role=\"tablist\"></ul>"));
// Transform the wizard wrapper by wrapping the innerHTML in the content wrapper, then prepending the stepsWrapper
wizard.attr("role", "application").wrapInner(contentWrapper).prepend(stepsWrapper)
.addClass(options.cssClass + " " + options.clearFixCssClass + verticalCssClass);
//Now that wizard is tansformed, select the the title and contents elements
var populatedContent = wizard.find('.content'),
stepTitles = populatedContent.children(options.headerTag),
stepContents = populatedContent.children(options.bodyTag);

ASP MVC Razor - FormValidation - #Html.ValidationMessageFor - Editor [duplicate]

This question already has an answer here:
attaching jquery validation to replacement element
(1 answer)
Closed 6 years ago.
Validation working on all other elements i used sofar but validation-message for editor does not show up. ModelState has correct error-state,
but no message can be seen on the form.
here is what i have:
MODEL:
[Required(AllowEmptyStrings = false, ErrorMessage = "Diese Feld muss angegeben werden.")]
[StringLength(8000,ErrorMessage = "Feld muss zwischen {2} und {1} Zeichen enthalten.", MinimumLength = 8)]
[DataType(DataType.MultilineText)]
[AllowHtml]
[Display(Name = "Beschreibung")]
public string Description { get; set; }
VIEW:
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
this also does not work:
#Html.ValidationMessageFor(model => model.Description)
when i do this in view:
#Html.ValidationMessageFor(model => model.Description, "test message")
it works - meaning, it shows "test message" - but i want the messages i defined in model...
---- here is some field that works as expected ----
MODEL:
[Required(ErrorMessage = "Dieses Feld muss angegeben werden.")]
[StringLength(25, MinimumLength = 2)]
[Display(Name = "KeyWord")]
public string Keyword { get; set; }
VIEW:
<div class="form-group">
#Html.LabelFor(model => model.Keyword, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Keyword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Keyword, "", new { #class = "text-danger" })
</div>
</div>
when field is empty and submit attempted, the required message is shown.
when field contains too-less or too many characters, and field is not in focus or submit is attempted, string-length message is shown ..
that's what i would like for the 2nd editor ...
----- end of working field -----
what am i doing wrong ?
thank you
SOLVED:
it was that "jQuery TE" was used to beautify the editor.
thank you #Stephen Muecke and #Varun Vasishtha for pushing me there ;)
There must be a javascript error that is restricting jquery validation to work, try to debug using Firebug in Firefox
Exclude the last "test message":
#Html.ValidationMessageFor(model => model.Description)
See the documentation: https://msdn.microsoft.com/en-us/library/system.web.mvc.html.validationextensions.validationmessagefor%28v=vs.118%29.aspx

Is it possible to add a class and a style to a Razor element

Is it possbile to add a style AND a class atrribute to a Razor element.
<div style="width:170px;float:left;">
#Html.DropDownListFor(m => m.SelectedPremise, Model.PremiseList, "Please select", new { #class = "selectpicker", data_style="btn-primary" ,style="width:100px;"})
</div>
This does not work...
Yes it is possible to add.
find below example for reference.
#Html.LabelFor(model => model.First, new Dictionary<string, object>() { { "class", "class-name" }, { "style", "display:none" } });

Resources