Change validation message in MVC at runtime - c#

I have a validation message for where I need to change the error message text at run time (when they click the submit button).
Based on what the id is passed in, the user has to send XML or a Query.
If they should send in a query, I want it to say: "The Query is required."
If they should send in xml, I want it to say: "The XML is required."
I've tried to clear the ModelState.Clear();
I've tried to NOT set the second parameter in ValidationMessageFor()... (usually it is "", but when I try to set it within there, then it automatically shows on the page when the page loads)
#Html.ValidationMessage("RawXmlOrQueryText", string.Format("The {0} field is required.", Model.Label), new { #class = "text-danger" })
if I do something like this, then it never shows period:
#Html.ValidationMessageFor(m => m.RawXmlOrQueryText, string.Format("The {0} field is required.", Model.Label), new { #class = "text-danger", style = "display:" + "none" + ";" })
Is there a better way to do this?
I want to be able to set the error message at run time and it to now show on the page until the user clicks the button.

Are you ok with using AddModelError()?
Assuming you are using this model:
public class IndexModel
{
public string QueryText { get; set; }
}
In your post method, add the following code:
var isXML = true; //oversimplification of your validation code
var someErrorMsg = isXML ? "The XML is required." : "The Query is required.";
ModelState.AddModelError(nameof(model.QueryText), someErrorMsg);
return View(model);

Related

Data validation message appears even when textbox has data

So I populated my ABCViewModel with data. Every single field of it had data.
One of its field is called Name. Name is required by using data annotations. [Required]
I passed ABCViewModel to my view, with the name field containing a string.
This view is actually used to edit ABCViewModel contents.
The html page appears, with the nametextbox containing the name. But the data validation message appears below the textbox.
[Name field is required]
When I use my mouse to click on the textbox to grant it focus, the validation message disappears.
Any one had this issue before?
[HttpPost]
public ActionResult Edit(ABCDetailsViewModel abcDetailsViewModel)
{
ABCViewModel abc = new ABCViewModel(abcDetailsViewModel);
return View(abc);
}
#model ABCViewModel
#using(Html.BeginForm("ABCUpdate", "Details", FormMethod.Post, new{name="form", id="form", #class="form-horizontal"}))
{
#Html.AntiForgeryToken()
#Html.LabelFor(model=>model=>Name, new{#class="control-label col-sm-2"})
#Html.TextBoxFor(model => model.Name, "", new{#style="width:100%;"})
#Html.ValidationMessageFor(model => Model.Name, "", new{#class = "alert-danger"})
.
.
.
}
Check whether you pass an object empty object with null values in your return View() method - recheck that you didn't set any default value for Name prop
If nothing works please post your cshtml and the controller code
In your Html.EditFor() method check that you are not binding any values - Thanks

Trouble with checkbox validation in Razor form

I am currently at an internship and am completely new to Razor and C# MVC. I am currently building a simple Razor form, but my validation is giving me grief for a check box.
Here is my model code:
[DisplayName("Sign me up for spam* ")]
[Range(typeof(bool), "true", "true", ErrorMessage = "You must sign up for spam.")]
public bool Check { get; set; }
Here is my Razor markup:
#Html.LabelFor(model => model.Check, new { #class = "" })
#Html.CheckBoxFor(model => model.Check, new { #class = "example1"})
Here is the generated HTML:
<input class="example1" data-val="true" data-val-range="You must sign up for spam." data-val-range-max="True" data-val-range-min="True" data-val-required="The Sign me up for spam* field is required." id="Check" name="Check" type="checkbox" value="true">
<input name="Check" type="hidden" value="false">
I know that Razor will generate both inputs automatically. My problem is that the validation is simply not working on the check box. The model state is always invalid because of it, and on the client side the error message appears when the box is checked and disappears when the box is unchecked. I have been googling for answers, but have come up short and my mentor doesn't know what is going screwy either.
It looks like a client side reversed issue. Add this jquery in your page and I think it will be fixed:
<script>
// extend range validator method to treat checkboxes differently
var defaultRangeValidator = $.validator.methods.range;
$.validator.methods.range = function(value, element, param) {
if(element.type === 'checkbox') {
// if it's a checkbox return true if it is checked
return element.checked;
} else {
// otherwise run the default validation function
return defaultRangeValidator.call(this, value, element, param);
}
}
</script>

Lost remaining record after validation error comes in MVC

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

Compare field not showing error message

I have got a model as below -
public string Password { get; set; }
[Compare("Password", ErrorMessage = "Password and Confirm Password have to be the same")]
public string ConfirmPassword { get; set; }
In my HTML, I am adding the code as
<label>Password</label>
<span class="req">*</span>
#Html.PasswordFor(x => x.Password, new { #class = "form-control form-control2", #required = "required" })
<p class="signuppace"></p>
<label>Confirm Password</label>
<span class="req">*</span>
#Html.PasswordFor(x => x.ConfirmPassword, new { #class = "form-control form-control2", #required = "required" })
The message for the required field gets displayed but here the ErrorMessage "Password and Confirm Password have to be the same" doesn't get displayed. I have already referred this 1,2 SO links. What am I doing wrong? Any help would be appreciated.
The don't think that the helper adds markup to display a validation error automatically, other than for client side validation using unobtrusive client validation which executes using JavaScript (Not server side).
You want to use #Html.ValidationMessageFor(x => x.ConfirmPassword) to show the error message or simply check for the error using the ModelState.
#if (ModelState.Errors["ConfirmPassword"] != null && !string.IsNullOrWhiteSpace(ModelState.Errors["ConfirmPassword"][0]))
{
// Display the first error message for this field
ModelState.Errors["ConfirmPassword"][0]
}
You don't show all relevant cshtml, but you need to display the validation message.
Either use #Html.ValidationSummary(excludePropertyErrors: false) to display all validation errors in one place, or put #Html.ValidationMessageFor(x => x.Password) near your input field.

hide the default value of a textBoxFor

Note - this is an asp.net MVC 4 application using Razor 2 views...
basically I have a textbox in a view waiting for the user to input data,
this data makes up the values for properties of a model which I want to save to the Db.
The data associated with this textbox has a [required] tab in the Model. I cannot save the model without a value for this textbox as the Model is not valid.
I know I can simply add #Value to the #HtmlTextBoxFor line, put this means that value is displayed to the user.
Is there away to have a default value hidden, so that the user only see's the placeholder text but the "value" will be saved to the Db.
Any ideas...?
textbox..
#Html.TextBoxFor(n => n.Article.Title, new { #class = "span4 m-wrap", rows = 1 , #placeholder = "Enter your News Articles main subject or Title here" , #Value = "Title"})
controller
if (ModelState.IsValid)
NewsArticle newNews = new NewsArticle();
newNews.Title = newsArticle.Article.Title;
You can add an ID to the textbox as follows:
#Html.TextBoxFor(n => n.Article.Title, new { #class = "span4 m-wrap", rows = 1 , #placeholder = "Enter your News Articles main subject or Title here" , #Value = "", #id="txtTitle"})
Then call following jquery function on form submit event
$(function(){
$("form").submit(function () {
if($("#txtTitle").val() == ""){
$("#txtTitle").val("Default Value");
}
});
});

Categories