I am new to ASP.NET MVC 5 and having some issues with binding only the multi-select section of the body during POST when submitting the form. The form renders correctly, with checkboxes being correctly selected. The form is scaffolded using visual studio (except the multi-select)
public class EditViewModel
{
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "LastName")]
public string LastName { get; set; }
public IList<RolesViewModel> Roles { get; set; }
}
public class RolesViewModel
{
public string RoleId { get; set; }
public string RoleName { get; set; }
public bool Selected { get; set; }
}
[HttpGet]
public async Task<ActionResult> Edit(string Id)
{...
var model = Mapper.Map<ApplicationUser, EditViewModel>(user);
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(EditViewModel model)
{
}
#model BloggingService.Web.Models.EditViewModel
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Edit</title>
</head>
<body>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Edit</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Roles, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#for (int i = 0; i < Model.Roles.Count; i++)
{
#Html.CheckBoxFor(x => #Model.Roles[i].Selected,"test1");
<div class="form-check">
<input type="hidden" asp-for="#Model.Roles[i].RoleId" />
<input type="hidden" asp-for="#Model.Roles[i].RoleName" />
<input type="checkbox" asp-for="#Model.Roles[i].Selected" class="form-check-input" checked="#Model.Roles[i].Selected" />
<label class="form-check-label" asp-for="#Model.Roles[i].Selected">
#Model.Roles[i].RoleName
</label>
</div>
}
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Would really appreciate any insight.
I have managed to find the correct and cleaner approach for accomplishing such tasks by utilizing the HTML helper methods inside my for loop and now the data are able to bind correctly during data-binding.
#Html.HiddenFor(x => #Model.Roles[i].RoleId);
#Html.HiddenFor(x => #Model.Roles[i].RoleName);
#Html.CheckBoxFor(x => #Model.Roles[i].Selected);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
When I click Edit button to submit the data it just refreshes the page. I have spent hours to solve the problem. Though it does not show any error and it does not change the database. I can not fix the problem why it is happening.
Model class for Student
public class Student
{
[Key]
public int StudentId { get; set; }
[Required]
[Display(Name = "Student Name")]
public string StudentName { get; set; }
[Required(ErrorMessage = "please enter Email")]
[Remote("IsEmailUnique","Student",ErrorMessage = "This Email is
already Exists")]
public string Email { get; set; }
[Required(ErrorMessage = "please fill up Address")]
[DataType(DataType.MultilineText)]
public string Address { get; set; }
[Required]
public int DepartmentId { get; set; }
public virtual Department Department { get; set; }
[Display(Name = "Date of Birth")]
[Required]
[DataType(dataType:DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}",
ApplyFormatInEditMode = true)]
public DateTime DoB { get; set; }
[Required]
[Remote("IsPhoneUnique", "Student", ErrorMessage = "This Phone is
already Exists")]
public string Phone { get; set; }
public string Gender { get; set; }
[Required]
[Display(Name = "Reg NO")]
[Remote("IsRegNoUnique", "Student", ErrorMessage = "This RegNo is
already Exists")]
public string RegNo { get; set; }
}
Controller for edit
[HttpGet]
public ActionResult Edit(int? id)
{
var student = db.Students.Find(id);
ViewBag.id = new SelectList(db.Departments, "DepartmentId", "
"DepartmentName");
return View(student);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Student student)
{
if (ModelState.IsValid)
{
db.Entry(student).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.id = new SelectList(db.Departments, "DepartmentId", "DepartmentName", student.DepartmentId);
return View(student);
}
View for Edit
#model CampusManagementApp.Models.Student
#{
ViewBag.Title = "Make A Booking";
HtmlHelper.ClientValidationEnabled = false;
}
<h2>Edit</h2>
#using (Html.BeginForm("Edit", "Student"))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Student</h4>
<hr />
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.StudentId)
<div class="form-group">
#Html.LabelFor(model => model.StudentName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StudentName)
#Html.ValidationMessageFor(model => model.StudentName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Address, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Address)
#Html.ValidationMessageFor(model => model.Address)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DepartmentId, "DepartmentId", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("DepartmentId",
(IEnumerable<SelectListItem>)ViewBag.id,
"Select department")
#Html.ValidationMessageFor(model => model.DepartmentId)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DoB, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DoB)
#Html.ValidationMessageFor(model => model.DoB)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Phone, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Phone)
#Html.ValidationMessageFor(model => model.Phone)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Gender, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<b>Male</b>#Html.RadioButton("Gender", "Male")
<b>Female</b>
#Html.RadioButton("Gender", "Female")
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
What can be done to solve the problem?
You have at least one validation error, because RegNo is required and is not even part of your view.
As suggested in the comments, best is to put a breakpoint on this line of your controller:
if (ModelState.IsValid)
And check if there are any other validation errors...
I have a partial view that returns a list of users address's, I need the user to be able to select one, then when they press "submit" along with the other details it takes the details from the selected address returns it to the controller, from there I know how to assign it where I want. How would I do this? Examples and help appreciated
Here is my controller for creating the order, view beneath;
[HttpPost]
public ActionResult AddressAndPayment(FormCollection values, string id)
{
var order = new Order();
TryUpdateModel(order);
//sets date and username
order.Username = User.Identity.Name;
order.OrderDate = DateTime.Now;
//Order gets saved
storeDB.Orders.Add(order);
storeDB.SaveChanges();
//Order gets processed
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.CreateOrder(order);
//Save again, total not saving properly until now
storeDB.SaveChanges();
return RedirectToAction("Complete",
new { id = order.OrderId });
}
VIEW
#model T_shirt_Company_v3.Models.Order
#{
ViewBag.Title = "Address And Payment";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.HiddenFor(x => x.OrderId)
#Html.HiddenFor(x => x.OrderDate)
#Html.HiddenFor(x => x.PaymentTransactionId)
#Html.HiddenFor(x => x.Total)
#Html.HiddenFor(x => x.Username)
<div class="form-horizontal">
<h2>Address And Payment</h2>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#{Html.RenderAction("Listofaddresses", "Checkout");}
<h2>Select Postage type</h2>
#Html.EnumDropDownListFor(model => model.PostageList, "-- Please select postage type --")
<h2>Payment</h2>
<div class="form-group">
#Html.LabelFor(model => model.cardDetails.FullName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.cardDetails.FullName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.cardDetails.FullName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.cardDetails.CardNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.cardDetails.CardNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.cardDetails.CardNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.cardDetails.CardExpireMonth, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="row">
<div class="col-md-1">
#Html.EditorFor(model => model.cardDetails.CardExpireMonth, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.cardDetails.CardExpireMonth, "", new { #class = "text-danger" })
</div>
<div class="col-md-1">
#Html.EditorFor(model => model.cardDetails.CardExpireYear, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.cardDetails.CardExpireYear, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.cardDetails.Cvc, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.cardDetails.Cvc, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.cardDetails.Cvc, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
Partial View
#model IEnumerable<T_shirt_Company_v3.Models.deliveryAddress>
#foreach (var item in Model)
{
<div style="width: 180px">
<div class="thumbnail">
<p>#Html.DisplayFor(modelItem => item.FirstName) #Html.DisplayFor(modelItem => item.LastName) </p>
<p>#Html.DisplayFor(modelItem => item.Address)</p>
<p>#Html.DisplayFor(modelItem => item.City)</p>
<p>#Html.DisplayFor(modelItem => item.PostalCode)</p>
<p>#Html.DisplayFor(modelItem => item.Country)</p>
</div>
</div>
}
Address Class
public class deliveryAddress
{
[Key]
[ScaffoldColumn(false)]
public int AdressId { get; set; }
[ScaffoldColumn(false)]
public string UsersAddress { get; set; }
[Required]
[StringLength(16, ErrorMessage = "Your name is too long")]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Your last name is required.")]
[StringLength(16, ErrorMessage = "Last name is too long.")]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required(ErrorMessage = "Address is required.")]
public string Address { get; set; }
[Required(ErrorMessage = "City is required.")]
public string City { get; set; }
[Required(ErrorMessage = "Postcode is required.")]
[Display(Name = "Post Code")]
public string PostalCode { get; set; }
[Required(ErrorMessage = "Country is required.")]
public string Country { get; set; }
[Required(ErrorMessage = "Phone home number is required.")]
[Display(Name = "Home Telephone")]
public string Phone { get; set; }
[Required(ErrorMessage = "Phone mobile number is required.")]
[Display(Name = "Mobile")]
public string Mobile { get; set; }
}
}
I'm trying to use Data Annotations in my MVC project (Mono/.NET 4.5). I've created my model and added all the appropriate annotations. I have my view and controller appropriately wired up. However, the validation just doesn't seem to be happening. I've tried everything I can find to no avail. As this is my first time working with Razor and Data Annotations, I imagine there is some setup piece I'm missing but I can't find it for the life of me. Here's my code:
Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace MyWebsite
{
public class RegisterViewModel : BaseViewModel
{
#region properties
[Required(ErrorMessage = "Required")]
[StringLength(50)]
[DisplayName("First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Required")]
[StringLength(100)]
[DisplayName("Last Name")]
public string LastName { get; set; }
[StringLength(50)]
[DisplayName("Display Name")]
public string DisplayName { get; set; }
[Required(ErrorMessage = "Required")]
[StringLength(255)]
[DisplayName("Email Address")]
public string EmailAddress { get; set; }
#endregion
#region ctor
public RegisterViewModel ()
{
}
#endregion
}
}
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MyWebsite.Controllers
{
public class AccountController : Controller
{
public ActionResult Register()
{
ViewData ["IsComplete"] = false;
ViewData ["RequiredVouches"] = WebSettings.RequiredVouches;
return View ();
}
[HttpPost]
public ActionResult Register(FormCollection formData)
{
if (ModelState.IsValid) {
//TODO: Put the data
ViewData ["IsComplete"] = true;
}
return View ();
}
}
}
View
#model SummerIsles.Web.RegisterViewModel
#section Styles {
<link href="~/Content/themes/base/Account.css" rel="stylesheet" type="text/css" />
}
#{
if((bool)#ViewData["IsComplete"]) {
<h1>Registration Request Complete!</h1>
<div class="page-message">
<p>
Confirmation message goes here
</p>
</div>
}
else {
<h1>Registration</h1>
<div class="page-message">
<p>
Instruction text goes here
</p>
</div>
using (Html.BeginForm()) {
#Html.ValidationSummary(false)
<fieldset>
<legend>Your Information</legend>
<div class="group column-1">
#Html.LabelFor(modelItem => #Model.FirstName)
#Html.EditorFor(modelItem => #Model.FirstName, new { htmlAttributes = new { #class="form-control" } } )
#Html.ValidationMessageFor(modelItem => #Model.FirstName)
#Html.LabelFor(modelItem => #Model.DisplayName)
#Html.EditorFor(modelItem => #Model.DisplayName, new { htmlAttributes = new { #class="form-control" } } )
#Html.ValidationMessageFor(modelItem => #Model.DisplayName)
</div>
<div class="group column-2">
#Html.LabelFor(modelItem => #Model.LastName)
#Html.EditorFor(modelItem => #Model.LastName, new { htmlAttributes = new { #class="form-control" } } )
#Html.ValidationMessageFor(modelItem => #Model.LastName)
#Html.LabelFor(modelItem => #Model.EmailAddress)
#Html.EditorFor(modelItem => #Model.EmailAddress, new { htmlAttributes = new { #class="form-control" } } )
#Html.ValidationMessageFor(modelItem => #Model.EmailAddress)
</div>
<div class="button-options">
<button id="btnSubmit" type="submit" formmethod="post" class="btn btn-danger">Submit</button>
<a id="btnCancel" href="~/" class="btn">Cancel</a>
</div>
</fieldset>
}
}
}
Also, I have added the jquery validation scripts to my layout file and have also enabled client validation in the web.confg.
Layout Header
<head>
<!--some other css and such-->
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobstrusive.min.js"></script>
</head>
Web.config
<appSettings>
<!--some other stuff-->
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
Basically, when I click submit, it thinks the model is perfectly valid (ModelState.IsValid returns true in the controller) and the validation stuff (which I would expect to fire before the post back to the controller) never seems to fire. I get no validation messages even with a completely blank form (despite having the "Required" data annotation). What am I missing?
#Html.ValidationMessageFor(modelItem => #Model.LastName)
should be
#Html.ValidationMessageFor(modelItem => modelItem.LastName)
for all your HtmlHelpers, including TextBoxFor and LabelFor etc.
Also
public ActionResult Register(FormCollection formData)
should be
public ActionResult Register(RegisterViewModel model)
in order for your server side ModelState.IsValid to work.
$(document).ready(function () {
$(".ChkBooks").click(function () {
var chkslst = $(".ChkBooks");
var CheckedList = "";
debugger;
$.each(chkslst, function (index, data) {
if (data.checked) {
CheckedList += data.value + ",";
}
});
$("#BookNames").val(CheckedList);
});
});
[Key]
public int Eno { get; set; }
[DisplayName("Employee Name")]
[Required(ErrorMessage = "Name is required")]
[RegularExpression(#"^[a-zA-Z]+$",ErrorMessage = "Pls Enter Only Charaters")]
[StringLength(100, MinimumLength = 3,ErrorMessage = "Name Length Minimun 3 is required")]
public string Ename { get; set; }
[DisplayName("Employee salary")]
//[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
[RegularExpression(#"^[0-9]*$", ErrorMessage = "Pls Enter Only Numbers")]
[Required(ErrorMessage = "salary is required")]
[Range(3000, 10000000, ErrorMessage = "Salary must be between 3000 and 10000000")]
public int salary { get; set; }
[DisplayName("Image")]
[Required(ErrorMessage = "Image is required")]
public HttpPostedFileBase Image { get; set; }
[DisplayName("Email")]
[Required(ErrorMessage = "Email is required")]
[RegularExpression(#"^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$", ErrorMessage ="Please Enter Valid EmailID")]
public string Email { get; set; }
[DisplayName("Password")]
[Required(ErrorMessage = "Password is required")]
[DataType(DataType.Password)]
public string Password { get; set; }
[DisplayName("ConfirmPassword")]
[Required(ErrorMessage = "Password is required")]
[Compare("Password", ErrorMessage = "Password is Not Matching")]
public string ConfirmPassword { get; set; }
[DisplayName("PHONENumber")]
[Required(ErrorMessage = "PhoneNmber is required")]
[RegularExpression(#"^[0-9]*$", ErrorMessage = "Pls Enter Only Numbers")]
[StringLength(10,ErrorMessage ="maxlimit 10")]
public string PhoneNmber { get; set; }
[DisplayName("Age")]
[RegularExpression(#"^[0-9]*$", ErrorMessage = "Pls Enter Only Numbers")]
[Required(ErrorMessage = "Age is required")]
public int Age { set; get; }
[DisplayName("Gender")]
[Required(ErrorMessage = "Gender is required")]
public bool Gender { get; set; }
[DisplayName("Date")]
[Required(ErrorMessage = "Date is required")]
public DateTime DateandTime { get; set; }
[DisplayName("BookNames")]
[Required(ErrorMessage = "Date is required")]
public List<string> BookNames { get; set; }
}
#{
ViewBag.Title = "Registration";
List<Books> BooksLists = (List<Books>)ViewBag.BooksList;
}
<h2>Registration</h2>
#*#using (Html.BeginForm())*#
#using (Html.BeginForm("Registration", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employees</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Ename, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Ename, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Ename, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.salary, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.salary, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.salary, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Image, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Image, new { #type = "file", #accept = "image/x-png,image/gif,image/jpeg" }) #*image/**#
#Html.ValidationMessageFor(model => model.Image, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PhoneNmber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.EditorFor(model => model.PhoneNmber, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.TextBoxFor(model => model.PhoneNmber, "{0:c}", new { #class = "required numeric", id = "CurrentBalance" })
#Html.ValidationMessageFor(model => model.PhoneNmber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Age, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Age, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Age, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Gender, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#*#Html.RadioButtonFor(m => m.Gender, "true") <label> Male </label>
#Html.RadioButtonFor(m => m.Gender, "false") <label> Female </label>*#
#Html.DropDownListFor(model => model.Gender, new SelectList(new List<Object>{
new { value = "" , text = "Select" },
new { value = 1 , text = "Male" },
new { value = 0 , text = "Female"} }, "value", "text", 0))
#Html.ValidationMessageFor(model => model.Gender, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DateandTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DateandTime, new { htmlAttributes = new { #class = "form-control", #type = "date" } })
#Html.ValidationMessageFor(model => model.DateandTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BookNames, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#if (Model != null)
{
for (int i = 0; i < #BooksLists.Count; i++)
{
#Html.CheckBox(Convert.ToString(#BooksLists[i].BookName), false, new { #class = "ChkBooks", style = "margin-left: 20px;vertical-align: 1px;width: 16px;height: 16px; ", #type = "checkbox", #value = Convert.ToString(#BooksLists[i].BookId) })
#BooksLists[i].BookName;
}
}
else
{
for (int i = 0; i < #BooksLists.Count(); i++)
{
#Html.CheckBox(Convert.ToString(BooksLists[i].BookName), false, new { #class = "ChkBooks", style = "margin-left: 20px;vertical-align: 1px;width: 16px;height: 16px; ", #type = "checkbox", #value = Convert.ToString(#BooksLists[i].BookId) })
#BooksLists[i].BookName;
}
}
<br />
#Html.TextBoxFor(m => m.BookNames, new { #class = "form-control", style = "display: none",#readonly = true })
#Html.ValidationMessageFor(model => model.BookNames, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
I have an actionmethod resetpassword which is of type get which returns a view. The method gets called from an actionlink button. To this view I am passing a user obj. Now when I click on the actionlink , it goes to the view but as I have applied validationfor the validations are getting fired automatically when the view is loaded. Is this because I am passing an obj of user to the view.? If that's the case, then how can i turn off the validations for HttpGet for that action method as I only want to load the inputs and when the user starts filling in the inputs then only validation should fire.
Action Method.
[ValidateInput(false)]
[HttpGet]
[ActionName("ResetPassword")]
public ActionResult ResetPassword(UserBE user)
{
user.Email = TempData["userEmail"].ToString();
return View(user);
}
View
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
#model XYZ.BE.UserBE
#{
ViewBag.Title = "ResetPassword";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>ResetPassword</h2>
#using (Html.BeginForm("ResetPassword", "User"))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true)
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DisplayFor(model=>model.Email)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.PasswordFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)
#Html.HiddenFor(model=>model.Email)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewPassword, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.PasswordFor(model => model.NewPassword)
#Html.ValidationMessageFor(model => model.NewPassword)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ConfirmedPassword, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.PasswordFor(model => model.ConfirmedPassword)
#Html.ValidationMessageFor(model => model.ConfirmedPassword)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Reset Password" class="btn btn-default" />
</div>
</div>
}
ActionLink BUtton
<h3>#Html.ActionLink("Reset Password", "ResetPassword")
Post Method
[HttpPost]
[ActionName("ResetPassword")]
public ActionResult ResetPasswordPost(UserBE user)
{
user = UserBL.AuthenticateUser(user);
if (!user.AuthenticUser || (user.Password==user.NewPassword))
{
return View(user);
}
else
{
return UserBL.ResetPassword(user)?View("LoginSuccessful",user):View(user);
}
}
Model
[Required(ErrorMessage = "Password is required")]
public string Password { get; set; }
private bool authenticUser = false;
public bool AuthenticUser
{
get { return authenticUser; }
set { authenticUser = value; }
}
[Required(ErrorMessage = "Password is required")]
public string NewPassword { get; set; }
[Required(ErrorMessage = "Confirm passord and NewPassWord does not match")]
[Compare("NewPassword")]
public string ConfirmedPassword { get; set; }
I just added the following to _layout and it worked.
#Scripts.Render("~/bundles/jqueryval")