How to apply a specific style to an invalid field? - c#

Suppose I have a field like this:
<div class="form-group">
<label for="fullname" asp-for="UserName">Username</label>
<input class="form-control"
type="text" name="username"
required asp-for="UserName">
<span asp-validation-for="UserName"></span>
</div>
inside my controller I added this error:
ModelState.AddModelError("username", "username already registered");
Now, I want apply the focus on the input field and also I want apply a red border, is possible do this only via MVC?

When the model validation fails and you return to the same view, the framework will add the input-validation-error CSS class to the input elements, for which the validation failed. In your case, you are adding the error message to the UserName field, so your UserName field input will get this new CSS class.
<input class="form-control input-validation-error" type="text" name="username"
required="" id="UserName" value="some value">
You can add any sort of styling you want to this CSS class as needed.
.input-validation-error
{
border-color:red;
}
Now setting the focus on a specific input field is a little tricky. The server code cannot do that. You have to do that on client side. But if there are multiple fields in the form with failed validation, which one you want to focus ? The first one, second one ? last one ?
Here is a quick sample to focus on the first input element with input-validation-error CSS class. The JavaScript code is executed on the jquery document.ready event.
$(function () {
$("input.input-validation-error").first().focus();
});
If you want to style the validation error message rendered by the validation helper (<span asp-validation-for="UserName"></span>), follow the same approach. When validation fails, the framework will change the CSS class of this span element to field-validation-error (from field-validation-valid). So all you have to do is, add the needed style definitions to that CSS class.
.field-validation-error
{
color:red;
}

Related

How to disable jquery validation on certain input fields

Is there any way to disbale jquery validation on certain input fields inside a form? So that it won't bother me with the 'red text under my input' or whenever I submit my form. I'm searching for a while now but without any succes. I tried using formnovalidate="formnovalidate" from this questions but also without any succes.
Here's my cshtml input code:
<div class="form-group">
<label asp-for="preExposure" class="control-label"></label>
<input asp-for="preExposure" id="preExposureInput" class="form-control" type="text"/>
<span asp-validation-for="preExposure" class="text-danger"></span>
</div>
Although I posted as a comment that it was pretty similar to the linked question, the most important part of that answer is below:
Once you have the jquery validation turned on for the form with the .validate() you can still configure the rules for the individual element that you want, and remove all the rules.
$('#myfield').rules('remove'); // removes all rules for this field

Html attribute based on server side variable?

I have something like this.
<input type="text">
I want enable/disable it based in certain variable value in server side.
I have tried this.
<input type="text" <%= DisableServiceInfo ? "disabled":"" %>/>
but not working.
I know this can be done.
<input type="text" disabled="<%= DisableServiceInfo ? "disabled":"invalid value" %>"/>
but this is not a valid mark-up. Because the only valid way to enable control is to remove disabled attribute.
I am not asking how value can be supplied based on variable but how attribute in injected
Please don't answer the ways to set it server side or by javascript. I just want to know if it is possible in this way?
Is this webforms? If you want to do this by the book, you can manually add an Id, and Runat="Server". Once you've done that, your control can be manipulated in your code-behind.
If your Id is ServiceInfo, you could do:
ServiceInfo.Attributes["disabled"] = "disabled";

Input data is not returning by passing through object

I am passing the input data from the .cshtml page to the action method.
Here is my .cshtml page:
#model passingdata
<form asp-controller="Home" method="post" asp-action="About" >
<button class="btn-danger" type="submit" value="Submit"></button>
<div class="form-group">
<label>
<input asp-for="date" placeholder="Date" class="col-md-8" />
</label>
<label>
Select from these Four Classes
<input type="radio" name="class" asp-for="classselect1" id="classselect1" value="classselect1" class="col-md-4" /> <p> #Model.classname1</p>
<input type="radio" name="class" asp-for="classselect2" id="classselect2" value="classselect2" class="col-md-4" /> <p> #Model.classname2</p>
<input type="radio" name="class" asp-for="classselect3" id="classselect3" value="classselect3" class="col-md-4" /> <p> #Model.classname3</p>
<input type="radio" name="class" asp-for="classselect4" id="classselect4" value="classselect4" class="col-md-4" /> <p> #Model.classname4</p>
</label>
</div>
</form>
And here is my controller code which is invoked when i Click on the button.
[HttpPost]
public IActionResult About(passingdata p)
{
ViewData["Message"] = "Your application description page.";
Teacher.classselect1 = p.classselect1;
Teacher.classselect2 = p.classselect2;
Teacher.classselect3 = p.classselect3;
Teacher.classselect4 = p.classselect4;
Teacher.date = p.date;
return View();
}
The input data like date and bool value from the radiobutton is not passing through the object of the class which contain these variables.
Please help me in this.
If i remember correctly, the Name attribute of each radiobutton is how .net MVC will map the values to your model.
In this case, all of your names are "class", which essentially means you have 1 form field named class with 4 options.
I would recommend using the html helper classes, because they will automatically create the proper html for you. The answer to this post should help: When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?
If you dont want to use the helper just remember that when you submit a form, the data that is posted is based on the name of each form field. .Net does some magic in the background to serialize your Model for you, but essentially you are just submitting data in the format "?prop1=val1&prop2=val2".
Update
I figure maybe I should clarify a little better why what you are doing is not working how you expect.
When you post or put data via a form, it passes the input fields (text box, radio button, checkbox, etc...) as either querystring params or are part of the body. Radio buttons work a little differently than other input type. For a radio button, there are multiple input elements, but only one of them is valid. That is handled by using the name attribute. In your case, all of the names are "class", which means that the only thing being passed to the server is a single "?class={val}" (val is the value of which ever radio button is selected).
If your passingdata model had a property called "class", it would be populated. If your goal is to populated all 4 of the classselect properties with different values, you would need the name of each radio button to be different. But if there was only one radio button with each name, then each property could only have 1 value. You would need multiple RadioButtons with the same name to have multiple values (only one of which is selectable for each property).
Hopefully that clarifies what is wrong and gets you in the right direction.

Disable Required attribute from code behind

I have two html input in one form, and I am setting them to required as follows:
<input id="email" name="textfield36" type="text" class="input3" runat="server" required="required" />
<input id="frEmail" name="textfield36" type="text" class="input3" runat="server" required="required" />
I need to set the Required attribute to false to one of the two inputs from c#. For example:
if (language == "English")
{
frEmail.Attributes.Add("required", "false");
}
else
{
email.Attributes.Add("required", "false");
}
This is causing an issue, because if the language is English, then the user only needs to fill the specified fields and the way it's happening now is that he's obliged to fill them all and vice versa. Note that on load I'm hiding the fields not relating to the language.
Can anyone help on this?
The required attribute is a Boolean attribute. That means the value is ignored. It's presence on the element all that matters. You need to remove the required attribute, not change its value.
email.Attributes.Remove("required");

Dynamically rendered MVC 3 validation not working

I'm rendering some input controls dynamically. I wrote a method like this
public override MvcHtmlString GetActionControl(HtmlHelper<ItemDetailsViewModel> helper)
{
return
helper.EditorFor(A => A.Triage.ProcessNumber) +
helper.ValidationMessageFor(a => a.Triage.ProcessNumber, "*")
}
And I'm calling this from the main CSTHML file like this:
<!-- Render Action Controls for each possible action -->
#foreach (IActionControl iac in WorkflowActionControls.GetActionControls(Model.WorkflowItem.CurrentState))
{
<div id="#("div" + iac.ControlName)" class="ui-corner-all ui-widget ui-widget-content" style="margin-top: 24px; padding: 15px;">
#iac.GetActionControl(this.Html)
</div>
}
Notice that I'm passing the current HtmlHelper to the GetActionControl() method.
Problem is, the generated output is only:
<input class="text-box single-line" id="Triage_ProcessNumber" name="Triage.ProcessNumber" type="text" value="" />
Ie, no "extended" validation fields, and no validation . Aditionally I've discovered that the helper.ValidationMessageFor() method returns NULL.
However, If I put the editor and the validationMessage on the .cshtml directly everything works like a charm:
#Html.EditorFor(a => a.Triagem.ProcessNumber)
#Html.ValidationMessageFor(a => a.Triagem.ProcessNumber, "*")
What am I doing wrong here? Shouldn't the end result of calling HtmlHelper.EditorFor be the same? I'm sorry if this is a lame question but there isn't much information on generating HTML markup dynamically in regards to MVC 3.
I've checked the common pitfalls and everything is OK: validation enabled on web.config, the model class has the proper validation attributes, etc.
Any help would be greatly appreciated :)
PS: I've simplified the pasted code and ommited the form.
I don't know if this will help you, but validation is rendered when Html.ViewContext.FormContext is not null. When i had same problem, i just initialized form context with new FormContext(); and it worked

Categories