Mvc 4 validation summary errors not displaying - asp.net-mvc

I am having trouble displaying validation summary, I only want to display errors in validation summary, not beside the field.
In my view i have,
#Html.ValidationSummary()
#Html.ValidationMessageFor(m =>m.Name)
in my controller i have
ModelState.AddModelError("Name",
"name is required");
Am i not supposed to get a validation error message? at the top?
I don't get what i am missing...
I am also including these script files..
jquery.validate.min.js
jquery.validate.unobtrusive.min.js

Try
#Html.ValidationSummary(false)
so that it will not exclude property errors.
OR
Try the method #xurca linked which is to add the model error with an empty key so it is not tied to a specific property.
ModelState.AddModelError(String.Empty, "name is required");

If you custom named your field like
#Html.TextBoxFor(model => model.Name, new { id = "staffSearchFilterName", value = "", **Name = "staffSearchFilterName"** })
then you have to use
#Html.ValidationMessage("staffSearchFilterName")

If your #Html.ValidationSummary() call is in a Partial view, DON'T pass data into the partial view like this:
#Html.Partial("_YourForm", Model, new ViewDataDictionary { { "Submit", true }})
Instead, add the key value pair to Html.ViewData collection first:
#{
Html.ViewData.Add(new KeyValuePair<string,object>("Submit",true));
}
then call the partial view:
#Html.Partial("_YourForm", Model, Html.ViewData)
this will allow the ModelState to propagate to the partial view properly.

Related

Required Validation Message MVC

I need to add a validation control in ASP MVC for a textbox. I used the #Html.ValidationMessage helper.
There is one textbox and I want to show the error If the value is not entered in that field.
I used the following code.
#Html.TextBox("txtStudentNumber", "4234234");
#Html.ValidationMessage("txtStudentNumber", "Please enter the student number", new { #class = "text-danger" })
The above message is always shown irrespective if the textbox has a value or not.
I need to validate if the student textbox is empty and also when the save button is clicked.
First of all, you have to use strongly types controls. i.e you should use TextBoxFor instead of TextBox and use ValidationMessageFor instead of ValidationMessage.
and then you have to bind the textbox with model. Try this :
Step 1: Create one model class "ClsStudent"
public class ClsStudent{public int studentNo {get;set;}}
Step 2: Bind the model student number in the view :
#model ClsStudent
#Html.TextBoxFor(m => m.studentNo)
#Html.ValidationMessageFor(m => m.studentNo, null, new { #class = "error" })
Validation on Submit Button :
Submit

How to FluentBootstrap validation in MVC

Is it possible to use validation messages in FluentBootstrap on form element level?
When I use:
#using (var form = Html.Bootstrap().Form().Begin())
{
#form.InputFor(m => m.Name)
#form.Submit()
}
There is no validation, except validation error class on input tag. I want to show validation message for Name property and has-error class on form-group container.
Just add #form.ValidationSummary() where you want the general validation summary to appear. There is an example of this as well as some other examples here: https://github.com/daveaglick/FluentBootstrap/blob/develop/FluentBootstrap.Tests.Web/Views/MvcTests/MvcForms.cshtml
If there is no particular reason to use InpuFor you can do the following.
#form.EditorFor(m => m.Name, addValidationMessage: true)
This will show what error message you put on your Name property's attribute.
Such as
[StringLength(50, ErrorMessage="Cannot be longer than 50 character.")]
public string Name { get; set; }
I personally use the base validation helper
#form.InputFor(m => m.Password, FormInputType.Password)
#Html.ValidationMessageFor(m => m.Password)
I can set the type of the input unlike the case when I use EditorFor

Second model in same view not posting to controller

With the help of several SO questions, I've figured out how to use two models on the same view, using the tuple form. At the top of my file is this:
#using Project.Models;
#{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
#model Tuple<Foo, Bar>
}
For the Foo stuff, it uses jQuery like this:
#Html.DisplayFor(tuple => tuple.Item1.ID)
and works fine. However, for my second model, it isn't displaying info, but is a submission form. Currently, this is what I have:
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "createFoo", #action = "/api/Foo" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="editor-field">
#Html.TextAreaFor(tuple => tuple.Item2.Text)
#Html.ValidationMessageFor(tuple => tuple.Item2.Text)<br />
</div>
<input type="submit" value="Post Response" />
}
Mind you, this is mostly copy paste from other views since I'm new to MVC and it worked fine with other forms. For my FooController, I have this:
public void Post([FromBody] Foo foo)
{
Foo existingFoo = this.fooRepository.GetFoo(foo.ID);
if (existingFoo != null)
{
// throw error
}
else
{
System.Diagnostics.Debug.WriteLine("MESSAGE POSTING: " + foo.Text);
}
}
When submitting from the view, the received foo isn't null (checked in other tests), but the foo.text is empty. I've tried lots of different inputs and such, but I'm just so unfamiliar with the #Html.* functions and ASP.net-MVC in general that I'm not sure where I could be going wrong.
If you need to see my repository code let me know, but I doubt it'd have an effect on this. Thanks in advance for any help.
There are 2 issues I can see with your code above:
The way the Html helper will output your fields and how that feeds into your api post
Not having your ID in the controller.
1: Outputting a field like this (#Html.TextAreaFor(tuple => tuple.Item2.Text)) will give the field the name "Item2.Text". This is an issue as that is what gets passed on the post. You will get form data with Item2.Text:dfsdsgdfg. This won't match when your API controller tries to bind. So, try outputting the text field with a set name:
#Html.TextArea("Text", #Model.Item2.Text)
2: Your Id field is not in the form... thus it won't be sent. Try using a hidden field:
#Html.Hidden("ID", #Model.Item1.ID)
Also, just a clarification, this (#Html.DisplayFor(tuple => tuple.Item1.ID)) is not jQuery.

ASP.NET MVC: Html Helper Form Seems to be Incorrect

all, I could use your help again. I'm currently attempting to use an HTML helper to create a from that will pass my model into the Operations controller's method, TaskEdit, seen below:
[HttpPost]
public ActionResult TaskEdit(TaskViewModel viewModel, bool? embedded)
{
// code
}
In the view, I am using the following Razor code to attempt to produce the form:
#using (Html.BeginForm("TaskEdit", "Operations", new { embedded = true, viewModel = Model }, FormMethod.Post, new { #class = "form-horizontal" }))
{
// form code
}
This didn't actually give me my instance of the model - it only passed the class back as if it were a static class. So I tried the following instead:
#using (Html.BeginForm("TaskEdit", "Operations", new { embedded = true, id = Model.TaskId }, FormMethod.Post, new { #class = "form-horizontal" }))
{
// form code
}
And the following form was produced (which confused me):
<form action="/<sitename>/Operations/TaskEdit/0?embedded=True" class="form-horizontal" method="post"> <!-- Form code --> </form>
Not only was I assuming that the form action would be more along the lines of "/<sitename>/Operations/TaskEdit?id=0&embedded=True", but when I try to submit the form, I get a server error about "No parameterless constructor defined for this object." Help?
A transcription from the comments:
The reason the URL results in /TaskEdit/0 is because of the way your routing is setup. You'll notice the route also defines an id which causes it to format it different than expected.
The best solution here is to use a strongly typed view:
1) Put your model on top of the view (#model TaskViewModel)
2) Remove the model parameter from your form
3) Use the built-in extensions to create form fields (Html.EditorFor(x => x.SomeField)) or use the field names if you're doing it manually: <input type="text" name="SomeField />
4) The model parameter in your controller's actionresult will now contain the form data

ASP.NET MVC 2 Html.TextAreaFor not updating on Edit

I have a form that lets the user enter in some text. It will be longer than a few characters so I want to use a TextArea instead of a TextBox.
The Html.TextBoxFor works without issue, and the Html.TextAreaFor works when I create the entry, but does not store the new value when I edit it and shows whatever the value was before I went to edit it upon saving.
On Page:
<div>
<label>Work Performed:</label>
<%: Html.TextAreaFor(model => model.WorkPerformed)%>
<%: Html.ValidationMessageFor(model => model.WorkPerformed) %>
</div>
Code Behind for Create:
maintPerformed.MaintDate = DateTime.Parse(Request.Form["MaintDate"]);
maintPerformed.WorkPerformed = Request.Form["WorkPerformed"];
maintPerformedRepository.Add(maintPerformed);
maintPerformedRepository.Save();
return RedirectToAction("Details", new { id = maintPerformed.ID });
Code Behind for Edit:
maintPerformed.MaintDate = DateTime.Parse(Request.Form["MaintDate"]);
maintPerformed.WorkPerformed = Request.Form["WorkPerformed"];
maintPerformedRepository.Save();
return RedirectToAction("Details", new { id = maintPerformed.ID });
What am I missing on the edit side of things?
In both cases you are redirecting to the Details action. So make sure that maintPerformedRepository.Save() actually does something and most importantly in your Details action look what value is fetched from the data store. I suspect that either the database is not updated or in your Details action you are fetching a wrong value for your model.
Remark: Instead of writing the ugly DateTime.Parse(Request.Form["MaintDate"]); and Request.Form["WorkPerformed"]; pass your view model as argument to your controller action and let the model binder populate it from the request values.

Resources