I want to display error messages dynamically i.e, when the cursor moves out of the field but not when the form is submitted.
My requirement is like this:-
I have to design a registration form with some fields like name,address,phone number,email,password etc.
i designed it & saved the data successfully in DB but what i exactly required in the sense i have to display error messages dynamically without using "ajax" as i have already stated ...
My code is like this:-
View:-
<div class="venfor_line5" popText><label>#Resources.Resources.VendorReg_phoneNumber<img src="~/images/star.png" /> </label>
#Html.TextBoxFor(model => Model.MobileNumber, new { #class = "input" })
#Html.ValidationMessageFor(model => model.MobileNumber)</div>
<div class="venfor_line1" popText = #Resources.Resources.VendorReg_emailHintStr>
<label>#Resources.Resources.VendorReg_email<img src="~/images/star.png" /> </label>
#Html.TextBoxFor(model => Model.Email, new { #class = "input" })
#Html.ValidationMessageFor(model => model.Email)</div>
I have gone through many references but not found exactly what i am looking for.Any help would be greatly appreciated. can anyone guide me in resolving this issue.
You could use jQuery's focusOut() method to perform validation. Something like:
$('#elementId').focusOut(function(){
//do validation here
});
If you are using unobtrusive jQuery validation you could eagerly enable it so that it is automatically triggered onblur without requiring the user to submit the form:
$(document).ready(function () {
var settngs = $.data($('form')[0], 'validator').settings;
settngs.onfocusout = function (element) { $(element).valid(); };
});
Related
I am developing a .NEt MVC application, have a form with razor view along with AngularJS inputs but ng_change is not working. Its working fine with normal HTML inputs. Below is the syntax
#Html.EditorFor(model => model.R10Length, new { #class="form-control fcus", step="any", min="1", ng_model= "conf.amr10length", ng_change= "fr15length()", ng_value= "#Request['r10length']" })
Working fine for
<input type="number" ng-model="conf.amr10length" step="any" min="1" maxlength="5" name="r10length" id="r10length" class="form-control fcus" placeholder="R10 Length" ng-change="fr15length()" value="#Request["r10length"]" required />
When value in textbox changes it calls the fr15length() function and is bind with a textbox.
You can use TextBoxFor.It's works fine.
#Html.TextBoxFor(model => model.R10Length, new { #class =
"form-control fcus", step = "any", min = "1", ng_model =
"conf.amr10length", ng_change = "fr15length()", ng_value =
"#Request['r10length']" })
The ng-value directive is used for setting the value of an element with an AngularJS expression.
If you just want to set the value with razor code use the value tag:
#Html.EditorFor(model => model.R10Length, new { #class="form-control fcus", step="any", min="1", ng_model= "conf.amr10length", ng_change= "fr15length()", value=Request["r10length"] })
Note that the value will be lost if in your controller you set $scope.conf.amr10length to anything as you've bound that element with ng-model.
I have one MVC project,containing user registration form which have 25-30 fields to fill. After filling form if user forgot to fill mandatory field then it will shows validation error. But remaining all fields loss their data.
I mentioned in controller like
if (!ModelState.IsValid)
{
ModelToDBclass obj = new ModelToDBclass();
objModel.Id = Convert.ToInt32(obj.GetMaxPaperId());
objModel.countryNameDB = obj.GetcountryName();
return View(objModel);
}
and finally it returns the blank view. but at runtime when it comes to
return View(objModel); , the model shows the data with every field, but when it comes to view it unable to show record in text boxes and dropdown. I used textbox like,
<div class="col-sm-2"><input type="text" class="form-control" name="ConsumerFName" id="txtConsumerFirstName" placeholder="First Name" />
#Html.ValidationMessageFor(m => m.ConsumerFName)</div>
so, please help me how can i display filled record after validation error
You should always use Html Helper
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" }, placeholder = "First Name", autofocus = "autofocus" })
Then only when the Model state is not valid, it will show the returned object values at the respective fields. Don't normal html tags.
Hope this helps
Our application (MVC5) has some very complex validation that needs to be done server side (compound capacity checks, workflow validation, and more). The problem we are running into is that once server side validation fails and returns to the same view, the client side never submits values for any fields again (0 for int, empty strings, etc.)
Our general pattern is as follows:
public ActionResult PerformSomeAction()
{
var model = GetActionTemplate();
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PerformSomeAction([Bind(Include = ActionTemplate.FIELDS)] ItemTemplate template)
{
string errorMessage;
if (ModelState.IsValid)
{
bool isValid = ValidateAndPerformAction(template, out errorMessage)
if(isValid)
return RedirectToAction("Action", "Controller");
}
// Reset non-bound fields from new template
var model = GetActionTemplate();
template.FieldValue = model.FieldValue
return View(template);
}
Our views don't have anything special in them, other than the fact that some of our editors are built with the Telerik Kendo library. However, the symptoms are seen for all controls, not just Kendo based ones.
A basic View layout for editing a field is as follows:
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.Kendo().TextBoxFor(model => model.Name).HtmlAttributes(new
{
title = ModelMetadata.FromLambdaExpression(model => model.Name, ViewData).Description
})
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
Does anyone have any suggestions on what we are doing wrong?
Note: While it could be argued that this validation could be triggered through AJAX or other service calls, we would prefer to do it with the post implementation that we are using.
Update:
After further research, it appears this has to do with Kendo and not MVC. If I switch my View to be the following:
#Html.EditorFor(model => model.Volume)
Instead of:
#Html.Kendo().NumericTextBoxFor(model => model.Volume).HtmlAttributes(new
{
#class = "",
title = ModelMetadata.FromLambdaExpression(model => model.PreBoilVolume, ViewData).Description
}).Value(Model.Volume)
Everything appears to work fine. So somewhere in that Kendo statement it fails to rebind when returning from the post. It doesn't matter if I set the value again manually, it will never send it back in.
I guess it is time to get rid of some Kendo statements and go back to a more basic UI.
What you "want" to do is a very basic scenario for MVC with failed validation.
The first one that always catches people is with drop down lists. The posted model, does not contain the list of items, so has to be re-populated after failed validation, and then passed back into the view on return.
When I can't solve things like this I start commenting stuff out and work forwards. So in this case strip your model back to one non-ID property and see if it will work. Then you can try and track down the culprit.
It looks like the selectedvalues are not set on the model. Try change these lines of code:
var model = GetActionTemplate();
template.FieldValue = model.FieldValue
return View(template);
to something like this:
var model = GetActionTemplate();
model.Selectedvalues = template.FieldValue ?
return View(model);
I want to make an editing function where you can add metafields (= specific fields for a category) to a category.
What I want to do in the view is
foreach (App.Models.Metafield field in Model.Category.Metafields)
{
<div class="field">
#Html.TextBoxFor(model => field.Name, new { #class = "form-control title" })
#Html.DropDownListFor(model => field.Type, Model.MetaTypes, new { #class = "form-control type" })
</div>
}
The problem is that the Metafields are not added to the viewModel when I hit the save button. So I guess the field.Name and field.Type should be replaced by something else..
This can't work this way because the sent form can't contain these dynamically generated fields with the same name.
However, you can collect the data from these dynamic fields using js and serialize it into a hidden field just before submitting the form, then you can parse it in your server side.
Here is an example with jquery:
$('#save-btn').click(function(e) {
$hidden = $("#hidden");
$hidden.val(getDynamicData());
});
function getDyanmicData() {
var data;
$fields = $(".field");
// get children and calculate data
return data;
}
This may be a bit too 'manual work', but I find it useful to know what's happening. For other solutions you can search form dynamic forms in ASP.NET MVC.
Please try this code
#for(int i=0;i<=Model.Category.Metafields.count();i++)
{
<div class="field">
#Html.TextBoxFor(m=> m[i].Name, new { #class = "form-control title" })
#Html.DropDownListFor(m=> m[i].Type, Model.MetaTypes, new { #class = "form-control type" })
</div>
}
Probably a simple question, but i cant seem to find the answer.
using MVC 2 i have a series of Html.ValidationFor controls. I want to assign a CSS class to the text and cant seem to do it.
<%= Html.TextBoxFor(Model => Model.Chest, new { #class = "textBoxMeasure" })%>
<%= Html.ValidationMessageFor(Model => Model.Chest) %>
if i try the same method as textboxfor i get errors because it requires a string, when i put a string in it still wont work!
thanks
I added a comment to the accepted answer, but I cannot to format it for better view. So, here is my already formatted comment from the accepted response.
I had similar case and I used solution from accepted answer. But I desired to use message from model annotation. I tried this:
#Html.ValidationMessageFor(Model => Model.Chest, null, new { #class = "text-danger" });
and it correctly worked for me. I used MVC4 with bootstrap.
There's a variant that takes htmlAttributes as the third argument (the second is the message that should be displayed, or you can use null for the default validation message)
Html.ValidationMessageFor(
Model => Model.Chest,
"Please enter a value",
new { #class = "redText" })
For more info see http://msdn.microsoft.com/en-us/library/ee721293%28v=vs.98%29.aspx
Use the classes assigned to the span tag holding the message. If the field is valid the class is field-validation-valid. If there is an error its field-validation-error.
I use
.field-validation-error {
color:Red;
}
simplest way to do this to put #Html.ValidationMessageFor in div tag and apply css to div tag
<div style="font-size:15px !important;">
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
This way the color range will be wider.
#Html.ValidationMessageFor(x => x.WriterName, "", new { #style = "color:red" })