Client side validation not working on password - asp.net-mvc

I Have the following register view
#model YFA.Models.RegisterViewModel
#{
ViewBag.Title = "Register";
}
<h2 class="col-md-offset-1">#ViewBag.Title</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-group">
<div class="row">
<div class="col-md-3 col-md-offset-1">
#Html.LabelFor(model => model.BranchId, htmlAttributes: new { #class = "control-label" })
#Html.DropDownListFor(model => model.BranchId, new SelectList(Model.Branches, "BranchId", "BranchName", 0), "Please Select", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.BranchId, "", new { #class = "text-danger" })
</div>
</div>
</div>
<h3 class="col-md-offset-1">Name</h3>
<div class="form-group">
<div class="row">
<div class="col-md-3 col-md-offset-1">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control", placeholder = "John" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
<div class="col-md-4">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control", placeholder = "Smith" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
</div>
<h3 class="col-md-offset-1">Contact Details</h3>
<div class="form-group">
<div class="row">
<div class="col-md-4 col-md-offset-1">
#Html.LabelFor(model => model.Mobile, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { #class = "form-control", placeholder = "07724 567890" } })
#Html.ValidationMessageFor(model => model.Mobile, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-3 col-md-offset-1">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control", placeholder = "me#provider.com" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
<div class="col-md-4">
#Html.LabelFor(model => model.ConfirmEmail, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.ConfirmEmail, new { htmlAttributes = new { #class = "form-control", placeholder = "me#provider.com" } })
#Html.ValidationMessageFor(model => model.ConfirmEmail, "", new { #class = "text-danger" })
</div>
</div>
</div>
<h3 class="col-md-offset-1">Dates</h3>
<div class="form-group">
<div class="row">
<div class="col-md-3 col-md-offset-1">
#Html.LabelFor(model => model.DateOfBirth, htmlAttributes: new { #class = "control-label" })
#Html.TextBoxFor(model => model.DateOfBirth, new { #class = "form-control", placeholder = "01/12/80" })
#Html.ValidationMessageFor(model => model.DateOfBirth, "", new { #class = "text-danger" })
</div>
<div class="col-md-2">
#Html.LabelFor(model => model.Joined, htmlAttributes: new { #class = "control-label" })
#Html.TextBoxFor(model => model.Joined, new { #class = "form-control", placeholder = "01/12/10" })
#Html.ValidationMessageFor(model => model.Joined, "", new { #class = "text-danger" })
</div>
</div>
</div>
<h3 class="col-md-offset-1">Password</h3>
<div class="form-group">
<div class="row">
<div class="col-md-3 col-md-offset-1">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
<div class="col-md-4">
#Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { #class = "text-danger" })
</div>
</div>
</div>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="col-md-offset-1 col-md-10">
<input type="submit" class="btn btn-default" value="Register" />
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(function () {
$("#DateOfBirth").datepicker({
format: "dd/mm/yyyy",
startDate: "-120y",
endDate: "-10y",
startView: 2,
calendarWeeks: true,
defaultViewDate: { year: 1975, month: 01, day: 01 }
});
});
$(function () {
$("#Joined").datepicker({
format: "dd/mm/yyyy",
startDate: "-20y",
endDate: "1y",
startView: 2,
calendarWeeks: true,
defaultViewDate: { year: 2010, month: 01, day: 01 }
});
});
</script>
}
The client side validation works fine for every field except the password field. it will warn if the password isn't the correct length but won't warn about the need for a capital or non alpha numeric character.
I'm using asp.net mvc identity.
The view model section for password is:
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
And the post controller is:
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var now = DateTime.Now;
UserManager.AddClaim(user.Id, new Claim(ClaimTypes.GivenName, model.FirstName));
//Add the new club details to the database
var Instructor = new Instructor
{
FirstName = model.FirstName,
LastName = model.LastName,
Joined = model.Joined,
Email = model.Email,
Mobile = model.Mobile,
BranchId = model.BranchId,
LGVDrv = model.LGVDrv,
MiniBusDrv = model.MiniBusDrv,
Operational = model.Operational,
ApplicationUserId = user.Id,
};
db.Instructors.Add(Instructor);
db.SaveChanges();
var currentUser = UserManager.FindByName(user.UserName);
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
When posting the form it returns the view because var result fair to succeed.

Following the comment above I amended the viewModel by adding a regular expression to it as follows:
[Required]
[RegularExpression(#"^(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8,20}$",
ErrorMessage = "Password is not valid, it must be between 8 - 20 characters and contain a number and a capital letter")]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }

Related

Editing cascading drop down list asp.net mvc 5

I have created a cascading dropdown list of category and subcategory
This is perfectly working when i create my product list it show both the option category and subcategory but
i am having a problem when i perform my Edit function on my edit page it shows category list but doesnt populate subcategory
thanks in advance
enter code here
This is view where you can see both category and subcategory dropdown list code
Create.cshtml
#model Masonic_Masoinc.Product
#{
ViewBag.Title = "Create";
}
<h2>Product</h2>
<h1>#ViewBag.IsSuccess</h1>
#using (Html.BeginForm("Create", "Home", FormMethod.Post, new { #class = "form-horizontal", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ProductName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ProductName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProductName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductCode, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ProductCode, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProductCode, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Price, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Price, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Price, "", 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">
<input type="file" name="file" value="file" />
#*#Html.EditorFor(model => model.Image, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.ValidationMessageFor(model => model.Image, "", new { #class = "text-danger" })
</div>
</div>
<hr />
<h2>Category</h2>
<div class="form-group">
#Html.LabelFor(model => model.Categories.CategoryName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#if (ViewBag.CategoryList != null)
{
#Html.DropDownListFor(model => model.CatId, new SelectList(ViewBag.CategoryList, "CatId", "CategoryName"), "Select Your Category", new { #Class = "form-control" })
}
#*#Html.EditorFor(model => model.Category.CategoryName, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.ValidationMessageFor(model => model.Categories.CategoryName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SubCategories.SubCategory, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SubCatId, new SelectList(""), "Sub-Category", new { #class = "form-control" })
#*#Html.EditorFor(model => model.Category.CategoryName, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.ValidationMessageFor(model => model.SubCategories.SubCategory, "", 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>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function () {
$("#CatId").change(function() {
$.get("/Home/GetSubCatList",
{ CatId: $("#CatId").val() },
function(data) {
$("#SubCatId").empty();
$.each(data,
function(index, row) {
$("#SubCatId")
.append("<option value='" + row.SubCatId + "'>" + row.SubCategory + "</option>");
});
});
});
});
</script>
this is action method in controller
controller
public JsonResult GetSubCatList(int catId)
{
MasonicMasterEntities db = new MasonicMasterEntities();
db.Configuration.ProxyCreationEnabled = false;
List<SubCategories> subcategory = db.SubCategories.Where(x => x.CatId == catId).ToList();
return Json(subcategory, JsonRequestBehavior.AllowGet);
}
Edit action method in conntroller
public ActionResult Edit(int id)
{
MasonicMasterEntities db = new MasonicMasterEntities();
var product = db.Product.SingleOrDefault(m => m.ProId == id);
if (product == null)
{
return HttpNotFound();
}
var category = db.Categories.ToList();
var subcategory = db.SubCategories.ToList();
var ViewModel = new ProductViewModel()
{
Products = product,
Categorieses = category,
SubCategorieses = subcategory
};
return View("Edit",ViewModel);
}

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);
}

how to pass an object to specific view with ASP.net MVC

I have a page wich it has a form and everythings works correctly.
my question is for when my model state is not valid, then how to return contact us to index view not create view
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,Email,Phone,Message,Date")] Contact_US contact_US)
{
if (ModelState.IsValid)
{
db.Contact_US.Add(contact_US);
db.SaveChanges();
MailMessage mail = new MailMessage();
mail.To.Add("");
mail.From = new MailAddress("");
mail.Subject = contact_US.Email;
string body = contact_US.Message;
mail.Body = "Phone:" + contact_US.Phone + "<br />Name:" + contact_US.Name +"<br />Email:"+contact_US.Email+ "<br /><br />" + body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential
("", "");// Enter seders User name and password
smtp.EnableSsl = true;
smtp.Send(mail);
TempData["ResultMessage"] = "Thank you for your enquiry and or enrolment. we will attend to this submission and come back to you soon";
TempData["TimeMessage"] = "Your entry was received on"+DateTime.Now;
return RedirectToAction("Index");
}
return View(contact_US);
}
in this situation if model state is not valid it looks fore create view but i don't want to have a create view . I just want to bring contact us to index page.
this is my index view
#using (Html.BeginForm("Create", "Contact_Us", FormMethod.Post, new { #id = "contactusform" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2 txtformat" })
<div class="col-md-12">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2 txtformat" })
<div class="col-md-12">
#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.Phone, htmlAttributes: new { #class = "control-label col-md-2 txtformat" })
<div class="col-md-12">
#Html.EditorFor(model => model.Phone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Phone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group hidden">
#Html.LabelFor(model => model.Date, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Date, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Message, htmlAttributes: new { #class = "control-label col-md-2 txtformat" })
<div class="col-md-12 contactusmsg">
#Html.TextAreaFor(model => model.Message, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Message, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group contactuspostbtn">
<div class="col-md-12">
<input id="postcontactusmessage" type="submit" value="Send" class="btn btn-default" />
</div>
</div>
</div>
}
Appreciate Any help
If you just want to call a view and pass in correct model then you can use overload with view name as in below cases:
Load view with Model:
return View("Index", contact_US); //Index is View name and contact_US is the Model.
Load view without Model:
return View("Index");
Make sure the Model expected by the view and what you are passing from the action are matching.
Ideally, except some specific cases better to stay close to MVC practices. Ex: If user provided data from Contact page then it would be nice and easily understood to redirect them back to Contact page instead of some other page. This need lot of caution especially while renaming the views etc.
Hope this help you.

Duplicate entries issue while using multiple partial views in single page

Hi I have two partial views in a single asp .net mvc page. When I submit entries using any of the partial view 2 entries got saved in database. If I disable any one partial view page works fine. Please help.
My Partial views look like this:
#using (Ajax.BeginForm("Create", "EnquiryForm", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divEnquiryFormMessage", LoadingElementId = "imgLoadingEnquiryForm" }))
{
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.AntiForgeryToken()
<div id="divEnquiryFormMessage">
</div>
<div class="form-group">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control", #placeholder = "Name" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "col-sm-12 text-danger" })
</div>
<div class="form-group">
#Html.EditorFor(model => model.ContactNumber, new { htmlAttributes = new { #class = "form-control", #placeholder = "Contact Number" } })
#Html.ValidationMessageFor(model => model.ContactNumber, "", new { #class = "col-sm-12 text-danger" })
</div>
<div class="form-group">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control", #placeholder = "Email" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "col-sm-12 text-danger" })
</div>
<div class="form-group">
#Html.TextAreaFor(model => model.Comments, new { htmlAttributes = new { #class = "form-control", #placeholder = "Comments" } })
#Html.ValidationMessageFor(model => model.Comments, "", new { #class = "col-sm-12 text-danger" })
</div>
<button type="submit" class="submit_btn">Submit</button>
<img style="display:none;" src="~/Content/Images/LoadingImage.gif" id="imgLoadingEnquiryForm" />
}
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
Second partial view:
#using (Ajax.BeginForm("Create", "MailingList", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "divMessage", LoadingElementId = "imgLoading" }))
{
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.AntiForgeryToken()
<div id="divMessage">
</div>
<div class="form-group">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control", #placeholder = "First Name" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "col-sm-12 text-danger" })
</div>
<div class="form-group">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control", #placeholder = "Last Name" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "col-sm-12 text-danger" })
</div>
<div class="form-group">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control", #placeholder = "Email" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "col-sm-12 text-danger" })
</div>
<div class="form-group">
#Html.EditorFor(model => model.ZipCode, new { htmlAttributes = new { #class = "form-control", #placeholder = "Zip Code" } })
#Html.ValidationMessageFor(model => model.ZipCode, "", new { #class = "col-sm-12 text-danger" })
</div>
<button type="submit" class="submit_btn">Submit</button><img style="display:none;" src="~/Content/Images/LoadingImage.gif" id="imgLoading" />
}
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
Both partial views are hitting different controllers and method still there is weird situation. I thing multiple "submit" buttons are causing problems, but I do not know how to resolve this issue.
Other ISSUE: after saving content I want to empty input controls in my partial view but it is also not working. I have tried ModelState.Clear()
My Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public string Create(EnquiryFormViewModel vObj)
{
System.Threading.Thread.Sleep(1000);
if (ModelState.IsValid)
{
EnquiryForm mObj = new EnquiryForm();
mObj.Name = vObj.Name;
mObj.ContactNumber = vObj.ContactNumber;
mObj.Email = vObj.Email;
mObj.Comments = vObj.Comments;
mObj.IsContacted = false;
mObj.CreatedOn = DateTime.Now;
string status = enquiryFormService.insertEnquiryForm(mObj);
ModelState.Clear();
return status;
}
else
{
return "<p class=\"bg-danger\">Oops there are some errors on page.</p>";
}
}
There Should Be Only 1 Ajax-unobtrusive in your whole page otherwise your controller will hit multiple times
You can use a success method after form have been submitted like this:-
#using (Ajax.BeginForm("Create", "MailingList", new AjaxOptions { onSuccess="ResetForm",HttpMethod = "POST", UpdateTargetId = "divMessage", LoadingElementId = "imgLoading" }))
And create a Function ResetForm() inside <script> tag and Inside function write
$('#formID')[0].reset();

While saving an image in my MVC WebApp, ModelState.IsValid always shows false

During Create, i always get the ModelState.IsValid as false and dont save my image in the database
In my model, the field for saving images is
[Required]
public byte[] BookingImage { get; set; }
In my controller, I have the following code:
public ActionResult Create([Bind(Include = "BookingId,BookingName,BookingDescription,ProviderId,EmployeeId,StatusId,BookingDuration,BookingTime, BookingImage, BookingRequestAmount,BookingReserveDeadline")] Booking booking, HttpPostedFileBase BookingImageHidden)
{
using (var ms = new MemoryStream())
{
BookingImageHidden.InputStream.CopyTo(ms);
booking.BookingImage = ms.ToArray();
}
if (ModelState.IsValid)
{
db.Booking.Add(booking);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.EmployeeId = new SelectList(db.Employee, "EmployeeId", "EmployeeName", booking.EmployeeId);
ViewBag.ProviderId = new SelectList(db.Providers, "ProviderId", "ProviderName", booking.ProviderId);
ViewBag.StatusId = new SelectList(db.Status, "StatusId", "StatusName", booking.StatusId);
return View(booking);
}
In my View, this is the code around the Image:
#model Sword.Models.Booking
#using (Html.BeginForm("Create", "bookings", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Booking</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.BookingName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BookingName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BookingName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BookingDescription, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BookingDescription, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BookingDescription, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProviderId, "ProviderId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ProviderId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ProviderId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EmployeeId, "EmployeeId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("EmployeeId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.EmployeeId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StatusId, "StatusId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("StatusId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.StatusId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BookingDuration, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BookingDuration, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BookingDuration, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BookingTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BookingTime, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BookingTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BookingImage, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BookingImage, new { htmlAttributes = new { #class = "form-control" } })
<input name="BookingImageHidden" type="file" />
#Html.ValidationMessageFor(model => model.BookingImage, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BookingRequestAmount, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BookingRequestAmount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BookingRequestAmount, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BookingReserveDeadline, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BookingReserveDeadline, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BookingReserveDeadline, "", 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>
In my model, the field for saving images is [Required] public byte[]
BookingImage { get; set; }
Why do you even have a property in your model for the image if you are going to manually be reading it.
So simply consider using view models with the proper types (please notice that I am bolding the word view model here):
public class BookingViewModel
{
[Required]
public HttpPostedFileBase BookingImage { get; set; }
... some other properties that you need populated from the client
}
and then in your controller action get rid of these hacks and use the view model:
public ActionResult Create(BookingViewModel bookingVm)
{
if (ModelState.IsValid)
{
// In the MapFromViewModel you will obviously only
// map the properties that you need to be populated
// in your domain model from the view model. That's where
// you should put the logic of reading the image stream into a
// byte array which is what your domain model expects.
Booking booking = MapFromViewModel(bookingVm);
db.Booking.Add(booking);
db.SaveChanges();
return RedirectToAction("Index");
}
...
}
You got into all those troubles because you didn't use view models in the first place but rather you had your controller actions take your domain models as parameter which is one of the worst MVC design patterns I have ever seen in my life.

Resources