Validate required model only - asp.net-mvc

I'm using two models, Login & Signup Model in a View.
public class Login
{
[Required(ErrorMessage ="User ID Required.")]
public string UserID { get; set; }
[Required(ErrorMessage ="Password Required")]
public string Password { get; set; }
}
public class SignUp
{
[Required (ErrorMessage ="User ID Required")]
public string UserID { get; set; }
[Required (ErrorMessage ="Name Required")]
public string Name { get; set; }
[Required (ErrorMessage ="Mail ID Required")]
public string MailID { get; set; }
[Required(ErrorMessage ="Password Required")]
public string Password { get; set; }
[Required(ErrorMessage ="Confirm Password Required")]
[Compare (nameof(Password), ErrorMessage ="Password does not match")]
public string ConfirmPassword { get; set; }
}
when I click Login button, it validates both the models. How to validate the model separately?
Used following codes in controller
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string Command, Login Login)
{
if (Command == "SIGNUP")
{
return RedirectToAction("Contact");
}
else
{
if (ModelState.IsValidField("USERID") && ModelState.IsValidField("PASSWORD"))
{
return RedirectToAction("About");
}
}
return View();
}
Index.cshtml VIEW CODE:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="HolderForm">
<div class="col-md-6">
<div class="form-horizontal">
<h4>Login</h4>
<hr />
<div class="form-group">
<div class="col-md-10">
#Html.EditorFor(o => o.Login.UserID, new { htmlAttributes = new { #class = "LoginEntry", #placeholder = "USER ID" } })<br>
#Html.ValidationMessageFor(o => o.Login.UserID,"", new {#class= "LoginValidation" } )
</div>
</div>
<div class="form-group">
<div class="col-md-10">
#Html.EditorFor(o => o.Login.Password, new { htmlAttributes = new { #class = "LoginEntry", #placeholder = "PASSWORD" } })<br>
#Html.ValidationMessageFor(o => o.Login.Password,"", new { #class = "LoginValidation" })
#ViewBag.Posted
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
#ViewBag.Posted
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit"
value="LOGIN"
id="btn_Login"
name="Command"
class="btn btn-default" />
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-horizontal">
<h4>SignUp</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="col-md-10">
#Html.EditorFor(o => o.SignUp.UserID, new { htmlAttributes = new { #class = "LoginEntry", #placeholder = "USER ID" } })<br>
#Html.ValidationMessageFor(o => o.SignUp.UserID,"", new { #class = "LoginValidation" } )
</div>
</div>
<div class="form-group">
<div class="col-md-10">
#Html.EditorFor(o => o.SignUp.Name, new { htmlAttributes = new { #class = "LoginEntry", #placeholder = "NAME" } })<br>
#Html.ValidationMessageFor(o => o.SignUp.Name, "", new { #class = "LoginValidation" })
</div>
</div>
<div class="form-group">
<div class="col-md-10">
#Html.EditorFor(o => o.SignUp.MailID, new { htmlAttributes = new { #class = "LoginEntry", #placeholder = "MAIL ID" } })<br>
#Html.ValidationMessageFor(o => o.SignUp.MailID, "", new { #class = "LoginValidation" })
</div>
</div>
<div class="form-group">
<div class="col-md-10">
#Html.EditorFor(o => o.SignUp.Password, new { htmlAttributes = new { #class = "LoginEntry", #placeholder = "PASSWORD", #type = "password" } })<br>
#Html.ValidationMessageFor(o => o.SignUp.Password, "", new { #class = "LoginValidation" })
</div>
</div>
<div class="form-group">
<div class="col-md-10">
#Html.EditorFor(o => o.SignUp.ConfirmPassword, new { htmlAttributes = new { #class = "LoginEntry", #placeholder = "CONFIRM PASSWORD", #type = "password" } })<br>
#Html.ValidationMessageFor(o => o.SignUp.ConfirmPassword, "", new { #class = "LoginValidation" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type= "submit" value="SIGNUP"
id="btn_Login"
name="Command"
class="btn btn-default" />
</div>
</div>
</div>
</div>
</div>
}
Above code place on the view using two different model.
Please help and also suggest me where to learn ASP.NET (Beginner level)?

you add Login and SignUp in one Form
#using (Html.BeginForm()){
...
}
try this
<div class="HolderForm">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="col-md-6">
<div class="form-horizontal">
<h4>Login</h4>
<hr />
<div class="form-group">
<div class="col-md-10">
#Html.EditorFor(o => o.Login.UserID, new { htmlAttributes = new { #class = "LoginEntry", #placeholder = "USER ID" } })<br>
#Html.ValidationMessageFor(o => o.Login.UserID,"", new {#class= "LoginValidation" } )
</div>
</div>
<div class="form-group">
<div class="col-md-10">
#Html.EditorFor(o => o.Login.Password, new { htmlAttributes = new { #class = "LoginEntry", #placeholder = "PASSWORD" } })<br>
#Html.ValidationMessageFor(o => o.Login.Password,"", new { #class = "LoginValidation" })
#ViewBag.Posted
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
#ViewBag.Posted
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit"
value="LOGIN"
id="btn_Login"
name="Command"
class="btn btn-default" />
</div>
</div>
</div>
</div>
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="col-md-6">
<div class="form-horizontal">
<h4>SignUp</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="col-md-10">
#Html.EditorFor(o => o.SignUp.UserID, new { htmlAttributes = new { #class = "LoginEntry", #placeholder = "USER ID" } })<br>
#Html.ValidationMessageFor(o => o.SignUp.UserID,"", new { #class = "LoginValidation" } )
</div>
</div>
<div class="form-group">
<div class="col-md-10">
#Html.EditorFor(o => o.SignUp.Name, new { htmlAttributes = new { #class = "LoginEntry", #placeholder = "NAME" } })<br>
#Html.ValidationMessageFor(o => o.SignUp.Name, "", new { #class = "LoginValidation" })
</div>
</div>
<div class="form-group">
<div class="col-md-10">
#Html.EditorFor(o => o.SignUp.MailID, new { htmlAttributes = new { #class = "LoginEntry", #placeholder = "MAIL ID" } })<br>
#Html.ValidationMessageFor(o => o.SignUp.MailID, "", new { #class = "LoginValidation" })
</div>
</div>
<div class="form-group">
<div class="col-md-10">
#Html.EditorFor(o => o.SignUp.Password, new { htmlAttributes = new { #class = "LoginEntry", #placeholder = "PASSWORD", #type = "password" } })<br>
#Html.ValidationMessageFor(o => o.SignUp.Password, "", new { #class = "LoginValidation" })
</div>
</div>
<div class="form-group">
<div class="col-md-10">
#Html.EditorFor(o => o.SignUp.ConfirmPassword, new { htmlAttributes = new { #class = "LoginEntry", #placeholder = "CONFIRM PASSWORD", #type = "password" } })<br>
#Html.ValidationMessageFor(o => o.SignUp.ConfirmPassword, "", new { #class = "LoginValidation" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type= "submit" value="SIGNUP"
id="btn_Login"
name="Command"
class="btn btn-default" />
</div>
</div>
</div>
</div>
</div>
}

Related

I tried Bootstrap DateTimePicker in ASP.NET MVC 5 but it's not working

I'm really new to ASP.NET MVC even the Web,I tried to build it on VS 2019,this is NOT the .net core project,it's the .NET for Win project,I tried to build a datetimepicker within the text input, so I tried to build to view like the below
#model log_viewer.Models.QueryParms
#{
ViewBag.Title = "QueryLog";
}
<h2>Query</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Query </h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.mdno, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.mdno, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.mdno, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.startdate, htmlAttributes: new { #class = "control-label col-md-2" })
#*<div class="col-md-10">
#Html.EditorFor(model => model.startdate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.startdate, "", new { #class = "text-danger" })
</div>*#
<div class="col-md-10">
<div class="input-group" id="datetimepicker">
#Html.EditorFor(model => model.startdate, new { htmlAttributes = new { #class = "datetimepicker form-control" } })
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
#Html.ValidationMessageFor(model => model.startdate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.enddate, htmlAttributes: new { #class = "control-label col-md-2" })
#*<div class="col-md-10">
#Html.EditorFor(model => model.enddate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.enddate, "", new { #class = "text-danger" })
</div>*#
<div class="col-md-10">
<div class="input-group" id="datetimepicker">
#Html.EditorFor(model => model.enddate, new { htmlAttributes = new { #class = "form-control" } })
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
#Html.ValidationMessageFor(model => model.enddate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Summit" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
My models are as below
public class QueryParms
{
[DisplayName("Contains Strings")]
public string mdno { get; set; }
[DisplayName("Begin Date")]
[DisplayFormat(DataFormatString = "{0:yyyy-mm-dd}", ApplyFormatInEditMode = true)]
public DateTime startdate { get; set; }
[DisplayName("End Date")]
[DisplayFormat(DataFormatString = "{0:yyyy-mm-dd}", ApplyFormatInEditMode = true)]
public DateTime enddate { get; set; }
}
When I clicked the datetime picker, it just not working, nothing happened

How can i show DisplayName label before and after editor (English + Arabic ) in MVC?

I want to create multi-language system using MVC (English and Arabic) , I want to use one view for both languages , i created the Login view based on the following model :
public partial class WEBSITE_USERS
{
[DisplayName("ID / Iqamam No - رقم الهوية او الاقامة")]
[Required(ErrorMessage ="This field is required يجب ادخال رقم الهوية المسجل في الملف الطبي ")]
public string ID_NO { get; set; }
[DisplayName("Mobile No - رقم الجوال")]
[Required(ErrorMessage = "Mobile No is required - يجب ادخال رقم الجوال المسجل في الملف ")]
public string MOBILE { get; set; }
[DisplayName("Medical Record No - رقم الملف")]
[Required(ErrorMessage = "File No is required يجب ادخال رقم الملف الطبي ")]
}
Now the DisplayName appeared on left side ,
How can i show the English label on left side and Arabic label on right side of editor to show like this for example :
ID/Iqama No ----------------- رقم الهوية او الاقامة
Now its appear all in left side like this :
ID / Iqamam No - رقم الهوية او الاقامة ---------------------------
this is the view code
#model kaashtaif.Models.WEBSITE_USERS
#{
ViewBag.Title = "Login Window - شاشة تسجيل الدخول";
}
<h2>Login</h2>
#using (Html.BeginForm("Authorise","Login",FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ID_NO, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ID_NO, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ID_NO, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MOBILE, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MOBILE, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MOBILE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PATIENT_NO, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PATIENT_NO, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PATIENT_NO, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-10">
<label>#Html.DisplayFor(model => model.LoginErrorMessage)</label>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Login" class="btn btn-default" />
<input type="reset" name="name" value="Clear" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
and this is screen shot of view
Fastest way of doing it is changing your markup and manually using Html.DisplayNameFor() then split that string up.
Repeat this process for the rest of the input fields/ form-group.
<div class="form-group">
<div class="col-md-3">
#Html.DisplayNameFor(x => x.ID_NO).ToString().Split('-')[0]
</div>
<div class="col-md-6">
#Html.EditorFor(model => model.ID_NO, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ID_NO, "", new { #class = "text-danger" })
</div>
<div class="col-md-3">
#Html.DisplayNameFor(x => x.ID_NO).ToString().Split('-')[1]
</div>
</div>
What's happening here is we're getting the value of DisplayName attribute which is [DisplayName("ID / Iqamam No - رقم الهوية او الاقامة")] and since you have a delimiter which is a hyphen, we're splitting the string into two using that - or hyphen then displaying the string by index.

Have a null check on Model but still getting Null object reference ASP.NET MVC

controller
public ActionResult EditProduct(int id)
{
ProductViewModel ViewModel = new ProductViewModel();
ViewModel.SingleProduct = DB.Prouducts.Where(x => x.ProductID == id).FirstOrDefault();
ViewModel.ImageList = DB.ImageGalleries.Where(x => x.ProductIdFk == id).ToList();
return View(ViewModel);
}
[HttpPost]
public ActionResult EditProduct(Prouduct product, IEnumerable<HttpPostedFileBase> thumb, ImageGallery images)
{
CategoryDropdown();
BrandDropdown();
if (ModelState.IsValid)
{
HttpPostedFileBase Image1 = thumb.FirstOrDefault();
product.ProductSlug = slug;
var userID = Convert.ToInt32(Session["UserID"]);
product.UserIdFk = userID;
DB.Entry(product).State = System.Data.Entity.EntityState.Modified;
DB.SaveChanges();
int LastInsertedID = product.ProductID;
foreach (var tmb in thumb)
{
if (tmb != null)
{
string FileName = tmb.FileName;
string Extenstion = Path.GetExtension(FileName);
if (Extenstion.ToLower() == ".jpeg" | Extenstion.ToLower() == ".jpg" | Extenstion.ToLower() == ".png" | Extenstion.ToLower() == ".webp")
{
FileName = FileName + DateTime.Now.ToString("yyyyMMddHHmmssfff") + Extenstion;
string ImageSavePath = Server.MapPath("/Content/Assets/Photos/");
tmb.SaveAs(Path.Combine(ImageSavePath + FileName));
string ThumbSavePath = Server.MapPath("/Content/Assets/Photos/Thumbs/");
ThumbGenration.ResizeStream(522, tmb.InputStream, Path.Combine(ThumbSavePath + FileName));
images.ImageName = FileName;
images.ImageThumb = FileName;
images.ProductIdFk = LastInsertedID;
//var userID = Convert.ToInt32(Session["UserID"]);
images.UserIdFk = userID;
DB.ImageGalleries.Add(images);
DB.SaveChanges();
TempData["Success"] = "Data Added Successfully!";
}
}
}
}
return View();
}
View
#model RentalServices.Models.ProductViewModel
#using (Html.BeginForm("EditProduct", "Product", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.SingleProduct.ProductID);
<div class="add-item-wrapper">
<h4>Listing Details</h4>
<hr class="noPadMar" />
<div class="add-item">
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<div class="col-md-12 col-sm-12 form-group">
#*<label class="col-sm-3 col-md-3 control-label">Title</label>*#
#Html.LabelFor(model => model.SingleProduct.Title, htmlAttributes: new { #class = "col-sm-3 col-md-3 control-label" })
<div class="col-sm-9">
#*<input type="text" class="form-control" placeholder="TITLE" />*#
#Html.EditorFor(model => model.SingleProduct.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SingleProduct.Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-12 col-sm-12 form-group">
#Html.LabelFor(model => model.SingleProduct.Price, htmlAttributes: new { #class = "col-sm-3 col-md-3 control-label" })
<div class="col-sm-9">
#Html.EditorFor(model => model.SingleProduct.Price, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SingleProduct.Price, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-12 col-sm-12 form-group">
#Html.Label("CATEGORY", htmlAttributes: new { #class = "col-sm-3 col-md-3 control-label" })
<div class="col-sm-9">
#Html.DropDownListFor(model => model.SingleProduct.CategoryIdFk, ViewBag.CategoryDropdown as SelectList, "CHOOSE CATEGORY", new { #class = "form-control", id = "CategoryID" })
#Html.ValidationMessageFor(model => model.SingleProduct.CategoryIdFk, "", new { #class = "text-danger" })
</div>
</div>
<div id="hide">
<div class="col-md-12 col-sm-12 form-group">
#Html.Label("BRAND", htmlAttributes: new { #class = "col-sm-3 col-md-3 control-label" })
<div class="col-sm-9">
#Html.DropDownListFor(model => model.SingleProduct.BrandIdFk, ViewBag.BrandDropdown as SelectList, "CHOOSE BRAND", new { #class = "form-control", id = "BrandID" })
#Html.ValidationMessageFor(model => model.SingleProduct.BrandIdFk, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-12 col-sm-12 form-group">
#Html.LabelFor(model => model.SingleProduct.Ram, htmlAttributes: new { #class = "col-sm-3 col-md-3 control-label" })
<div class="col-sm-9">
#Html.EditorFor(model => model.SingleProduct.Ram, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SingleProduct.Ram, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-12 col-sm-12 form-group">
#Html.LabelFor(model => model.SingleProduct.Processor, htmlAttributes: new { #class = "col-sm-3 col-md-3 control-label" })
<div class="col-sm-9">
#Html.EditorFor(model => model.SingleProduct.Processor, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SingleProduct.Processor, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-12 col-sm-12 form-group">
#Html.Label("CONDITION", htmlAttributes: new { #class = "col-sm-3 col-md-3 control-label" })
<div class="col-sm-9">
#Html.DropDownListFor(model => model.SingleProduct.Conditon, selectList, "CHOOSE CONDITION", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SingleProduct.Conditon, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-12 col-sm-12 form-group">
#Html.LabelFor(model => model.SingleProduct.Location, htmlAttributes: new { #class = "col-sm-3 col-md-3 control-label" })
<div class="col-sm-9">
#Html.EditorFor(model => model.SingleProduct.Location, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SingleProduct.Location, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-md-12 col-sm-12 form-group">
#Html.LabelFor(model => model.SingleProduct.Description, htmlAttributes: new { #class = "col-sm-3 col-md-3 control-label" })
<div class="col-sm-9">
#Html.TextAreaFor(model => model.SingleProduct.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SingleProduct.Description, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
</div>
</div>
<div class="image-gallery-wrapper">
<div class="img-gallery">
#if (Model.ImageList.Any())
{
foreach (var item in Model.ImageList)
{
<div class="img-wrapper">
<p>Image 1</p>
<div class="img-box">
<input type="file" name="thumb" value="" class="file-style" onchange="readURL(this)" ; />
<img src="/Content/Assets/Photos/Thumbs/#item.ImageName" alt="your image" id="imgName" value="#item.ImageName" />
<button id="RemoveImage">Remove Image</button>
</div>
</div>
}
}
</div>
</div>
<div class="text-center">
<button type="submit" class="roundSubmitBtn" style="background:#7048f0 !important;font-size:14px !important; margin-top:40px;">SUMBIT <i class="fa fa-arrow-right"></i></button>
</div>
}
As i added my code i am getting null exception error.but i have a check of null or not so why i am getting this null object reference error.
and i have also tried Count() and !=null in IF statement.i am getting erro while i submit form and error is null exception error so tell me where i am wrong
By inspecting POST action method provided in question, the problem seem coming from return View() statement which returns same view page as in GET action method but without returning viewmodel class instance, which causing ProductViewModel.ImageList contains null value.
The brief code below shows the problem:
[HttpPost]
public ActionResult EditProduct(Prouduct product, IEnumerable<HttpPostedFileBase> thumb, ImageGallery images)
{
CategoryDropdown();
BrandDropdown();
if (ModelState.IsValid)
{
// image processing and saving to DB
}
// the view returned without viewmodel
// this will trigger NullReferenceException because ProductViewModel.ImageList is not reassigned yet
return View();
}
Therefore, you should reassign ProductViewModel.ImageList property after saving posted data into database, and return the same view together with new ProductViewModel instance (or redirect to another action if necessary by following PRG pattern with RedirectToAction):
[HttpPost]
public ActionResult EditProduct(Prouduct product, IEnumerable<HttpPostedFileBase> thumb, ImageGallery images)
{
CategoryDropdown();
BrandDropdown();
if (ModelState.IsValid)
{
// image processing and saving to DB
}
// create viewmodel instance
var ViewModel = new ProductViewModel();
ViewModel.ImageList = ...; // reassign ImageList property here
return View(ViewModel);
}

MVC Client side validation are not working in partial view

I have a partial view which gets populated in modal body of my home page of MVC project. Partial view holds the login form as follows -
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-xs-6">
<div class="well">
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="col-md-12">
#Html.LabelFor(model => model.UserEmailId, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.UserEmailId, new { htmlAttributes = new { #class = "form-control", placeholder = "example#gmail.com" } })
#Html.ValidationMessageFor(model => model.UserEmailId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-12">
#Html.LabelFor(model => model.UserPassword, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.UserPassword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="remember" id="remember"> Remember login
</label>
</div>
</div>
<button type="button" class="btn btn-success btn-block" onclick="location.href='#Url.Action("Login", "Home")'">
Login
</button>
</div>
</div>
<div class="col-xs-6">
<p class="lead">Sign up with</p>
<ul class="list-unstyled" style="line-height: 2">
<li><span class="fa fa-check text-success"></span> See all your orders</li>
<li><span class="fa fa-check text-success"></span> Fast re-order</li>
<li><span class="fa fa-check text-success"></span> Save your favorites</li>
<li><span class="fa fa-check text-success"></span> Fast checkout</li>
<li><span class="fa fa-check text-success"></span> Get a gift <small>(only new customers)</small></li>
<li><u>Read more</u></li>
</ul>
</div>
</div>
}
I am using a partial classes to define my data validations for the models(so that they wont get missed if I update my db first models) -
public class UserMetadata
{
[Display(Name ="Username")]
[EmailAddress(ErrorMessage ="Please enter your email address")]
[Required(ErrorMessage ="Required field")]
public string UserEmailId { get; set; }
[Display(Name ="Password")]
[DataType(DataType.Password)]
[Required(ErrorMessage = "Username is required")]
[StringLength(15, ErrorMessage = "Must be between 8 and 15 characters", MinimumLength = 8)]
public string UserPassword { get; set; }
}
The validations are not working on the client side. They are not getting triggered. Am I missing some script reference?
I already have "ClientValidationEnabled" set to true in my web.config.
Please help. Thanks!
Edit -
The following is all included in my layout -
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>
<script src="https://use.fontawesome.com/2d83329334.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
Hi please check below code for reference
1. Model
public class UserMetadata
{
[Display(Name = "Username")]
[EmailAddress(ErrorMessage = "Please enter your email address")]
[Required(ErrorMessage = "Required field")]
public string UserEmailId { get; set; }
[Display(Name = "Password")]
[DataType(DataType.Password)]
[Required(ErrorMessage = "Username is required")]
[StringLength(15, ErrorMessage = "Must be between 8 and 15 characters", MinimumLength = 8)]
public string UserPassword { get; set; }
}
2. Controller
public class UserDataController : Controller
{
// GET: Contacts/UserData
public ActionResult Index()
{
var userData = new UserMetadata();
return View(userData);
}
}
view and Javascript
#model UserMetadata
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
#using (Html.BeginForm())
{
<div class="row">
<div class="col-xs-6">
<div class="well">
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text- danger" })
<div class="form-group">
<div class="col-md-12">
#Html.LabelFor(model => model.UserEmailId, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.UserEmailId, new { htmlAttributes = new { #class = "form-control", placeholder = "example#gmail.com" } })
#Html.ValidationMessageFor(model => model.UserEmailId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-12">
#Html.LabelFor(model => model.UserPassword, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.UserPassword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="remember" id="remember"> Remember login
</label>
</div>
<button type="button" class="btn btn-success btn-block" onclick="loginUser();">
Login
</button>
</div>
</div>
</div>
</div>
}
<script>
function loginUser()
{
if($('form').valid())
{
//redirect to some action like window.location=somerootPath+/login/home
}
else
{
//not valid
}
}
OutPut
Ensure the highlighted js are loaded except jquery UI.
One way of solution is:
In the html editor add 'required' field as below
#Html.EditorFor(model => model.UserEmailId, new { htmlAttributes = new { #class = "form-control", placeholder = "example#gmail.com",#required="required" } })
and no need of Html.ValidationMessageFor() for this.

Form doesn't work stay on the same page when I click submit

I am creating a feedback page, I want this page to go to sent page once I click the submit button. I have been trying this code, when I click submit, it just stays on the same page...
This is my view:
#using (Html.BeginForm("Feedback", "Home", FormMethod.Post))
{
#Html.ValidationSummary()
#Html.AntiForgeryToken()
#Html.ValidationSummary("", new {#class = "text-danger"})
<div class="form-group">
#Html.LabelFor(m => m.Name, new {#class = "col-md-2 control-label"})
<div class="col-md-10">
#Html.TextBoxFor(m => m.Name, new {#class = "form-control", placeholder = "Your Name"})
</div>
</div>
#Html.ValidationSummary("", new {#class = "text-danger"})
<div class="form-group">
#Html.LabelFor(model => model.Email, "Email", new {#class = "control-label col-sm-2"})
<div class="col-md-10">
#Html.EditorFor(m => m.Email, new {htmlAttributes = new {#class = "form-control", placeholder = "Email Address"}})
</div>
</div>
#Html.ValidationSummary("", new {#class = "text-danger"})
<div class="form-group">
#Html.LabelFor(m => m.Cell, new {#class = "col-md-2 control-label"})
<div class="col-md-10">
#Html.EditorFor(m => m.Cell, new {htmlAttributes = new {#class = "form-control", placeholder = "Phone Number", type = "text"}})
</div>
</div>
#Html.ValidationSummary("", new {#class = "text-danger"})
<div class="form-group">
#Html.LabelFor(m => m.Message, new {#class = "col-md-2 control-label"})
<div class="col-md-10">
#Html.TextBoxFor(m => m.Message, new {#class = "form-control", placeholder = "Comments", rows = "4"})
</div>
</div>
<div class="col-sm-6 col-sm-offset-3">
<div class="btn-toolbar">
<button class="btn-raised btn-primary btn" id="submit">Submit
<div class="ripple-container"></div>
</button>
<button class="btn btn-default">Cancel</button>
</div>
</div>
}
My controller:
[HttpGet]
public ActionResult Feedback()
{
ViewBag.Message = "Your contact page.";
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Feedback(FeedbackViewModel model)
{
if (!ModelState.IsValid)
{
var item = new FeedbackViewModel()
{
Name = model.Name,
Email = model.Email,
Cell = model.Cell,
Message = model.Message,
};
// TODO: Add success message to ViewBag / Data so notification will be displayed
return RedirectToAction("Sent");
}
// TODO Send email in c#
return View(model);
}
My model:
public class FeedbackViewModel
{
[Required]
public string Name { get; set; }
[Required]
[EmailAddress]
public String Email { get; set; }
[MinLength(10)]
[StringLength(13, ErrorMessage = "Please enter a valid phone number")]
public string Cell { get; set; }
[Required]
[StringLength(200, ErrorMessage = "Please enter more than 20 characters and less than 200", MinimumLength = 20)]
public string Message { get; set; }
}
you use !ModelState.IsValid, you must use ModelState.IsValid
if (ModelState.IsValid)
{
var item = new FeedbackViewModel()
{
Name = model.Name,
Email = model.Email,
Cell = model.Cell,
Message = model.Message,
};
//TODO: Add success message to ViewBag / Data so notification will be displayed
return RedirectToAction("Sent");
}
//TODOL Send email in c#
return View(model);
Then add __ #Html.ValidationMessageFor(..)__ to view like that
#using (Html.BeginForm("Feedback", "Home", FormMethod.Post))
{
#Html.ValidationSummary()
#Html.AntiForgeryToken()
#Html.ValidationSummary("", new {#class = "text-danger"})
<div class="form-group">
#Html.LabelFor(m => m.Name, new {#class = "col-md-2 control-label"})
<div class="col-md-10">
#Html.TextBoxFor(m => m.Name, new {#class = "form-control", placeholder = "Your Name"})
#Html.ValidationMessageFor(m => m.Name)
</div>
</div>
#Html.ValidationSummary("", new {#class = "text-danger"})
<div class="form-group">
#Html.LabelFor(model => model.Email, "Email", new {#class = "control-label col-sm-2"})
<div class="col-md-10">
#Html.EditorFor(m => m.Email, new {htmlAttributes = new {#class = "form-control", placeholder = "Email Address"}})
#Html.ValidationMessageFor(m => m.Email)
</div>
</div>
#Html.ValidationSummary("", new {#class = "text-danger"})
<div class="form-group">
#Html.LabelFor(m => m.Cell, new {#class = "col-md-2 control-label"})
<div class="col-md-10">
#Html.EditorFor(m => m.Cell, new {htmlAttributes = new {#class = "form-control", placeholder = "Phone Number", type = "text"}})
#Html.ValidationMessageFor(m => m.Cell)
</div>
</div>
#Html.ValidationSummary("", new {#class = "text-danger"})
<div class="form-group">
#Html.LabelFor(m => m.Message, new {#class = "col-md-2 control-label"})
<div class="col-md-10">
#Html.TextBoxFor(m => m.Message, new {#class = "form-control", placeholder = "Comments", rows = "4"})
#Html.ValidationMessageFor(m => m.Message)
</div>
</div>
<div class="col-sm-6 col-sm-offset-3">
<div class="btn-toolbar">
<input type="submit" value="Submit" class="btn-raised btn-primary btn" />
<button class="btn btn-default">Cancel</button>
</div>
</div>
}

Resources