Model Validation in ASP.NET MVC - asp.net-mvc

I am not getting validation messages? Any idea how to resolve? please take a look at the view, the model, and the controller code below. I also attached the js files maybe im missing files?
#model MvcApplication1.Models.Assesment
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
#using (Html.BeginForm())
{
#Html.TextBoxFor(m => m.name)
#Html.ValidationMessageFor(m=>m.name,"*Hello")
}
<input type="submit" value="submit" />
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
namespace MvcApplication1.Models
{
public class Assesment
{
[Required]
public string name { get; set; }
}
}
public class RegisterController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Assesment assesment)
{
return View();
}
}

Your <input type="submit"> should be inside the form.
Also, you should pass the invalid model to the view when handling the POST
[HttpPost]
public ActionResult Index(Assesment assesment)
{
return View(assesment);
}
By the way, a typical HttpPost action looks like this:
[HttpPost]
public ActionResult Index(Assesment assesment)
{
if( ModelState.IsValid )
{
// Handle POST data (write to DB, etc.)
//...
// Then redirect to a new page
return RedirectToAction( ... );
}
// show the same view again, this time with validation errors
return View(assesment);
}

Related

#Html.ValidationMessageFor is not working

//Index Page (view) /Employee/Index
#model DataAnotaionExample.Models.Employee
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<form action="./Add">
Enter Name=#Html.TextBoxFor(m=>Model.Name)
#Html.ValidationMessageFor(m=>Model.Name)
<input type="submit" value="Submit" />
</form>
//Employee Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace DataAnotaionExample.Controllers
{
public class EmployeeController : Controller
{
// GET: Employee
public ActionResult Index()
{
return View();
}enter code here
}
}
Model Class Employee.cs
namespace DataAnotaionExample.Models
{
public class Employee
{
[Required]
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
}
This is my code, If I keep the Name field blank then it will not throw the error like the field is required.
This Code Created in Asp.Net MVC5 Framework
make sure you have added
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script
at the end of your layout page:
First you have add razor like this
#model DataAnotaionExample.Models.Employee
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<form action="./Add">
//this one
#Html.ValidationSummary(true)
Enter Name=#Html.TextBoxFor(m=>Model.Name)
#Html.ValidationMessageFor(m=>Model.Name)
<input type="submit" value="Submit" />
</form>
Then you should like validation script like this in your "_Layout.cshtml" page
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
Or you can use this script in your App_Start->BundleConfig
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js",
"~Scripts/jquery.validate.js",
"~/Scripts/jquery.validate.unobtrusive.js"
));
I hope this code is useful for you.

ASP.NET Core MVC model binding to list returns empty list in POST method? [duplicate]

I have a really wierd issue with MVC.
My models keeps getting submitted empty.
And it's probably really simple, but I just can't find the issue.
My model looks like this:
public class LoginModel
{
public string Username;
public string Password;
}
My controller like this:
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(LoginModel loginTest)
{
if (loginTest.Username != "x" && loginTest.Password != "y")
{
ModelState.AddModelError("a", "Login failed.");
return View(loginTest);
}
else
{
return RedirectToAction("Home", "Welcome");
}
}
And the view is also very simple, like this.
#model LoginSolution.Models.LoginModel
#{
Layout = null;
}
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Login</title>
</head>
<body>
#using (Html.BeginForm("Login", "Home"))
{
<div> <span>Username : </span>
#Html.EditorFor(model => model.Username)
<br />
<span>Password : </span>
#Html.EditorFor(model => model.Password)
<br />
#Html.ValidationSummary()
<br />
<input type="submit" value="Login" name="Login" />
</div>
}
</body>
</html>
This is not a question about security or best practice.
This is just a question regarding why the model keeps returning itself as empty upon submitting.
Your model contains fields, not properties (no getter/setter) so the model binder cannot set the values. Change your model to
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
}

Model change in post action not visible in Html.TextBoxFor?

This must be something very obvious but for me it looks very strange. I have simple controller, model with one property, and view which displays value of property and renders editor for that property. When I click the button, form is posted and exclamation mark is appened to property. This exclamation mark is visible in my view but only in p tag, not in input tag rendered by Html.TextBoxFor().
Why Html.TextBoxFor() ignores that I updated my model in post action?
Is there any way to change this behavior of Html.TextBoxFor()?
View
#model ModelChangeInPostActionNotVisible.Models.IndexModel
#using (Html.BeginForm())
{
<p>#Model.MyProperty</p>
#Html.TextBoxFor(m => m.MyProperty)
<input type="submit" />
}
Model
namespace ModelChangeInPostActionNotVisible.Models
{
public class IndexModel
{
public string MyProperty { get; set; }
}
}
Controller
namespace ModelChangeInPostActionNotVisible.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new IndexModel { MyProperty = "hi" });
}
[HttpPost]
public ActionResult Index(IndexModel model)
{
model.MyProperty += "!";
return View(model);
}
}
}
HTML after clicking on submit button
<form action="/" method="post"> <p>hi!</p>
<input id="MyProperty" name="MyProperty" type="text" value="hi" /> <input type="submit" />
</form>
This is by design.
The helper methods are using the ModelState, thus if the response of your request is using the same Model, it will display the value that was posted.
This is to allow you to render the same view in the situation where the validation would have failed.
To make sure you display the new information add : ModelState.Clear(); before you return.
Read more here : http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx
namespace ModelChangeInPostActionNotVisible.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new IndexModel { MyProperty = "hi" });
}
[HttpPost]
public ActionResult Index(IndexModel model)
{
model.MyProperty += "!";
ModelState.Clear();
return View(model);
}
}
}
Yan Brunet is absolutely correct that the variable needs to be removed from the ModelState in order to be modified in the controller. You don't have to clear the entire ModelState, though. You could do the following to remove just the variable to want to modify:
ModelState.Remove("MyProperty");
This would be useful in case you wanted to retain other values which the user had entered.

ValidationMessageFor not showing errors

I have this class:
public class Product
{
[Required(ErrorMessage = "empty name")]
public string Name { get; set; }
[Required(ErrorMessage = "empty description")]
public string Description { get; set; }
}
and I have a ResponseProduct which is shown in view:
public class ProductInsertVM
{
public string Message = "Success";
public Product Product;
}
In my view I have this:
#using (Html.BeginForm()){
#Html.ValidationSummary(false)
#Html.TextBoxFor(m => m.Product.Description)
#Html.ValidationMessageFor(m => m.Product.Description)
}
What I want to know is why ValidationMessageFor doest'n work? !! only ValidationSummary works. If I respond with a Product, so it works.
The code you provided should work fine if the following conditions are met.
1) You have reference to the jQuery validation scripts in your view
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
2) On the form submit, you are calling the ModelState.IsValid property and hence validating the model passed to the action method
[HttpPost]
public ActionResult CarList(CarList model)
{
if (ModelState.IsValid)
{
//Save or whatever you want to do
}
return View(model);
}
Was missing this line in the _Lahout.cshtml
#Scripts.Render("~/bundles/jqueryval")
Complete:
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval") <------------
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)

Why can't I HtmlDecode in ASP.NET MVC 3

Here is the scenario. I want to use CKEditor for a rich text field on a form, but for whatever reason I cannot get the contents from the textarea to the server and back to the page without encoding problems. Here is the little sample program I wrote up to try and figure out what is going on. First, my view model:
HomeViewModel.cs
namespace CkEditorTest.Models
{
public class HomeViewModel
{
[Required]
[DataType(DataType.Html)]
[Display(Name = "Note")]
public string Note { get; set; }
}
}
Now my controller:
HomeController.cs
using System.Web.Mvc;
using CkEditorTest.Models;
namespace CkEditorTest.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new HomeViewModel());
}
[HttpPost]
[ValidateInput(false)]
public ActionResult Index(HomeViewModel model)
{
return View(model);
}
}
}
And finally, my view:
Index.cshtml
#model CkEditorTest.Models.HomeViewModel
#{
ViewBag.Title = "CKEditor Test";
}
#section head
{
<script type="text/javascript" src="#Url.Content("~/Scripts/ckeditor/ckeditor.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/ckeditor/adapters/jquery.js")"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#Note").ckeditor();
});
</script>
}
<h2>CKEditor Test</h2>
#using (Html.BeginForm())
{
#Html.LabelFor(m => m.Note)<br /><br />
#Html.TextAreaFor(m => m.Note)<br />
<input type="submit" />
}
#if (!String.IsNullOrEmpty(Model.Note))
{
<div id="noteText">#Model.Note</div>
}
No matter what I do, I cannot display the Model.Note property as html on my view. By the time it reaches the view it is HTML encoded (i.e. <p> etc...). Here is what the form looks like pre-post:
pre-post http://www.matthewkimber.com/images/so/pre-post.png
And here is what the result is in the div below the "Submit" button:
post result http://www.matthewkimber.com/images/so/posted.png
I've set a breakpoint within Visual Studio and it shows as bare angle brackets (no encoding on HTML elements, just characters).
breakpoint results http://www.matthewkimber.com/images/so/dataInsideTheActionMethod.png
This, of course, is the stripped down test. I've tried encoding it, decoding it both in the view and in the controller to no avail.
By default everything is encoded when you use razor. I think you're looking for the Raw method.
It would also be a good idea to check the response using Fiddler or Firebug.
Try this:
#Html.DisplayTextFor(modelItem => item.Note)
You can also use HtmlString("")

Resources