How Send Multiple Rows by using multiple models in ASP.NET MVC - asp.net-mvc

public partial class Sale
{
public int Sale_id { get; set; }
public string Order_No { get; set; }
public string Customer_name { get; set; }
public string Customer_phone { get; set; }
public string Customer_address { get; set; }
public string Payment_method { get; set; }
public double Total_amout { get; set; }
public bool Status_bit { get; set; }
public string Created_by { get; set; }
public System.DateTime Created_date { get; set; }
public string Modified_by { get; set; }
public System.DateTime Modified_date { get; set; }
}
public partial class SalesDetail
{
public int Sales_detail_id { get; set; }
public string Order_No_cp { get; set; }
public int Product_id { get; set; }
public double Unit_price { get; set; }
public int Quantity { get; set; }
public double LineTotal { get; set; }
public virtual Product Product { get; set; }
}
I Combined two model (Sales & SalesDetail)
public class Combined
{
public virtual Sale MCombined_Sales { get; set; }
public virtual SalesDetail MCombined_SalesDetail { get; set; }
}
Controller
public ActionResult Client()
{
Session["SysDateTime"] = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
Session["CrruntUser"] = "Testing";
ViewBag.Product_id = new SelectList(db.Products, "Product_id", "Product_name");
return View();
}
[HttpPost]
public ActionResult Add(Combined model)
{
if (ModelState.IsValid == true)
{
var MCombined_Sales = new Sale
{
Order_No = model.MCombined_Sales.Order_No,
Customer_name = model.MCombined_Sales.Customer_name,
Customer_phone = model.MCombined_Sales.Customer_phone,
Customer_address = model.MCombined_Sales.Customer_address,
Payment_method = model.MCombined_Sales.Payment_method,
Total_amout = model.MCombined_Sales.Total_amout,
Status_bit = model.MCombined_Sales.Status_bit,
Created_by = model.MCombined_Sales.Created_by,
Created_date = model.MCombined_Sales.Created_date,
Modified_by = model.MCombined_Sales.Modified_by,
Modified_date = model.MCombined_Sales.Modified_date,
};
var MCombined_SalesDetail = new SalesDetail
{
Order_No_cp = model.MCombined_SalesDetail.Order_No_cp,
Product_id = model.MCombined_SalesDetail.Product_id,
Unit_price = model.MCombined_SalesDetail.Unit_price,
Quantity = model.MCombined_SalesDetail.Quantity,
LineTotal = model.MCombined_SalesDetail.LineTotal,
};
using (var context = new Entities())
{
context.Sales.Add(MCombined_Sales);
MCombined_Sales.Sale_id = MCombined_Sales.Sale_id;
context.SalesDetails.Add(MCombined_SalesDetail);
context.SaveChanges();
ModelState.Clear();
}
}
return View();
}
View ( With using namespace:- #model ASH_POS.Models.Merge.Combined)
#using (Html.BeginForm(new { #id = "registerFormId", #class = "form-horizontal", role = "form" })) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="card">
<h4 class="text-center">Sale</h4>
<div id="Detail" class="row visually-hidden">
<div class="col">
<div class="form-group">
#Html.LabelFor(model => model.MCombined_Sales.Status_bit, htmlAttributes: new { #class = "control-label " })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.MCombined_Sales.Status_bit)
#Html.ValidationMessageFor(model => model.MCombined_Sales.Status_bit, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="col">
<div class="form-group">
#Html.LabelFor(model => model.MCombined_Sales.Created_by, htmlAttributes: new { #class = "control-label " })
<div class="col-md-10">
#Html.EditorFor(model => model.MCombined_Sales.Created_by, new { htmlAttributes = new { #class = "form-control", #Value = Session["CrruntUser"], #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.MCombined_Sales.Created_by, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col">
<div class="form-group">
#Html.LabelFor(model => model.MCombined_Sales.Created_date, htmlAttributes: new { #class = "control-label " })
<div class="col-md-10">
#Html.EditorFor(model => model.MCombined_Sales.Created_date, new { htmlAttributes = new { #class = "form-control", #Value = Session["SysDateTime"], #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.MCombined_Sales.Created_date, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col">
<div class="form-group">
#Html.LabelFor(model => model.MCombined_Sales.Modified_by, htmlAttributes: new { #class = "control-label " })
<div class="col-md-10">
#Html.EditorFor(model => model.MCombined_Sales.Modified_by, new { htmlAttributes = new { #class = "form-control", #Value = Session["CrruntUser"], #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.MCombined_Sales.Modified_by, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col">
<div class="form-group">
#Html.LabelFor(model => model.MCombined_Sales.Modified_date, htmlAttributes: new { #class = "control-label " })
<div class="col-md-10">
#Html.EditorFor(model => model.MCombined_Sales.Modified_date, new { htmlAttributes = new { #class = "form-control", #Value = Session["SysDateTime"], #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.MCombined_Sales.Modified_date, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="card-title">
<div class="form-group">
#Html.LabelFor(model => model.MCombined_Sales.Order_No, htmlAttributes: new { #class = "control-label " })
<div class="col-md-10">
#Html.EditorFor(model => model.MCombined_Sales.Order_No, new { htmlAttributes = new { #class = "form-control", #required = true, #Value = "1500" } })
#Html.ValidationMessageFor(model => model.MCombined_Sales.Order_No, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col">
<div class="form-group">
#Html.LabelFor(model => model.MCombined_Sales.Customer_name, htmlAttributes: new { #class = "control-label " })
<div class="col-md-10">
#Html.EditorFor(model => model.MCombined_Sales.Customer_name, new { htmlAttributes = new { #class = "form-control", #required = true, #Value = "N/A" } })
#Html.ValidationMessageFor(model => model.MCombined_Sales.Customer_name, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col">
<div class="form-group">
#Html.LabelFor(model => model.MCombined_Sales.Customer_phone, htmlAttributes: new { #class = "control-label " })
<div class="col-md-10">
#Html.EditorFor(model => model.MCombined_Sales.Customer_phone, new { htmlAttributes = new { #class = "form-control", #Value = "N/A" } })
#Html.ValidationMessageFor(model => model.MCombined_Sales.Customer_phone, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col">
<div class="form-group">
#Html.LabelFor(model => model.MCombined_Sales.Customer_address, htmlAttributes: new { #class = "control-label" })
<div class="col-md-10">
#Html.EditorFor(model => model.MCombined_Sales.Customer_address, new { htmlAttributes = new { #class = "form-control", #Value = "N/A" } })
#Html.ValidationMessageFor(model => model.MCombined_Sales.Customer_address, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
#Html.LabelFor(model => model.MCombined_Sales.Payment_method, htmlAttributes: new { #class = "control-label " })
<div class="col-md-10">
#Html.EditorFor(model => model.MCombined_Sales.Payment_method, new { htmlAttributes = new { #class = "form-control", #Value = "Cash" } })
#Html.ValidationMessageFor(model => model.MCombined_Sales.Payment_method, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col">
<div class="form-group">
#Html.LabelFor(model => model.MCombined_Sales.Total_amout, htmlAttributes: new { #class = "control-label " })
<div class="col-md-10">
#Html.EditorFor(model => model.MCombined_Sales.Total_amout, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.MCombined_Sales.Total_amout, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
</div>
<div class="card-footer">
<table id="tblProduct" class="table" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th>Order No</th>
<th>Product Name</th>
<th>Per Pice Price</th>
<th>Quantity</th>
<th>Amount</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" readonly value="" placeholder="Enter Order No " id="textBox_Order_No_cp" class="form-control" /></td>
<td><input type="text" value="1" placeholder="Search Product " id="textBox_Product_id" class="form-control" /></td>
<td><input type="number" value="15" min="0" placeholder="Enter Unit Price Product " id="textBox_Unit_price" class="form-control" /></td>
<td><input type="number" value="" step="1" min="1" placeholder="Enter Quantity" id="textBox_Quantity" class="form-control" /></td>
<td><input type="number" min="1" readonly value="" placeholder="Line Total" id="textBox_LineTotal" class="form-control" /></td>
<td><input type="button" id="btnAddProduct" value="Add" class="btn btn-sm" /></td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
#Html.EditorFor(model => model.MCombined_SalesDetail.Order_No_cp, new { htmlAttributes = new { #class = "form-control", #placeholder = "Order Number" } })
#Html.ValidationMessageFor(model => model.MCombined_SalesDetail.Order_No_cp, "", new { #class = "text-danger" })
</td>
<td>
#Html.EditorFor(model => model.MCombined_SalesDetail.Product_id, new { htmlAttributes = new { #class = "form-control", #placeholder = "ID" } })
#Html.ValidationMessageFor(model => model.MCombined_SalesDetail.Product_id, "", new { #class = "text-danger" })
</td>
<td>
#Html.EditorFor(model => model.MCombined_SalesDetail.Unit_price, new { htmlAttributes = new { #class = "form-control", #placeholder = "Unit Price", #min = "0" } })
#Html.ValidationMessageFor(model => model.MCombined_SalesDetail.Unit_price, "", new { #class = "text-danger" })
</td>
<td>
#Html.EditorFor(model => model.MCombined_SalesDetail.Quantity, new { htmlAttributes = new { #class = "form-control", #placeholder = "Quantity", #type = "number", #min = "1" } })
#Html.ValidationMessageFor(model => model.MCombined_SalesDetail.Quantity, "", new { #class = "text-danger" })
</td>
<td>
#Html.EditorFor(model => model.MCombined_SalesDetail.LineTotal, new { htmlAttributes = new { #class = "form-control", #placeholder = "LineTotal", } })
#Html.ValidationMessageFor(model => model.MCombined_SalesDetail.LineTotal, "", new { #class = "text-danger" })
</td>
<td></td>
</tr>
</tfoot>
</table>
</div>
<div id="btns">
<div class="form-group dataTables_wrapper">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn " id="AddClient" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="reset" value="Reset" class="btn" id="AddClient" />
</div>
</div>
<input type="submit" value="Testing Multi Row Table" class="btn btn-info close" id="btnTesting" />
</div>
</div> }
Use jQuery For Handle Multiple Models
$("#AddClient").click(function () {
var MCombined_Sales = {
Order_No: $('##Html.IdFor(model => model.MCombined_Sales.Order_No)').val(),
Customer_name: $('##Html.IdFor(model => model.MCombined_Sales.Customer_name)').val(),
Customer_phone: $('##Html.IdFor(model => model.MCombined_Sales.Customer_phone)').val(),
Customer_address: $('##Html.IdFor(model => model.MCombined_Sales.Customer_address)').val(),
Payment_method: $('##Html.IdFor(model => model.MCombined_Sales.Payment_method)').val(),
Total_amout: $('##Html.IdFor(model => model.MCombined_Sales.Total_amout)').val(),
Status_bit: $('##Html.IdFor(model => model.MCombined_Sales.Status_bit)').val(),
Created_by: $('##Html.IdFor(model => model.MCombined_Sales.Created_by)').val(),
Created_date: $('##Html.IdFor(model => model.MCombined_Sales.Created_date)').val(),
Modified_by: $('##Html.IdFor(model => model.MCombined_Sales.Modified_by)').val(),
Modified_date: $('##Html.IdFor(model => model.MCombined_Sales.Modified_date)').val()
};
var MCombined_SalesDetail = {
Order_No_cp: $('##Html.IdFor(model => model.MCombined_SalesDetail.Order_No_cp)').val(),
Product_id: $('##Html.IdFor(model => model.MCombined_SalesDetail.Product_id)').val(),
Unit_price: $('##Html.IdFor(model => model.MCombined_SalesDetail.Unit_price)').val(),
Quantity: $('##Html.IdFor(model => model.MCombined_SalesDetail.Quantity)').val(),
LineTotal: $('##Html.IdFor(model => model.MCombined_SalesDetail.LineTotal)').val()
};
var model = {
"MCombined_Sales": MCombined_Sales,
"MCombined_SalesDetail": MCombined_SalesDetail
}
$.ajax({
type: "POST",
url: "/Customer/Add",
data: model,
dataType: "json",
success: function (r) {
alert("id: " + r.Sale_id.toString());
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
I try use jQuery For Send Multiple Rows to db butt no success
$("body").on("click", "#btnAddProduct", function () {
//Reference the Name and Country TextBoxes.
var textBox_Order_No_cp = $("#textBox_Order_No_cp");
var textBox_Product_id = $("#textBox_Product_id");
var textBox_Unit_price = $("#textBox_Unit_price");
var textBox_Quantity = $("#textBox_Quantity");
var textBox_LineTotal = $("#textBox_LineTotal");
//Get the reference of the Table's TBODY element.
var tBody = $("#tblProduct > TBODY")[0];
//Add Row.
var row = tBody.insertRow(-1);
//Add textBox_Order_No_cp cells.
var cell = $(row.insertCell(-1));
cell.html(textBox_Order_No_cp.val());
//Add textBox_Product_id cell.
var cell = $(row.insertCell(-1));
cell.html(textBox_Product_id.val());
//Add textBox_Unit_price cell.
var cell = $(row.insertCell(-1));
cell.html(textBox_Unit_price.val());
//Add textBox_Quantity cell.
var cell = $(row.insertCell(-1));
cell.html(textBox_Quantity.val());
//Add textBox_LineTotal cell.
var cell = $(row.insertCell(-1));
cell.html(textBox_LineTotal.val());
//Add Button cell.
cell = $(row.insertCell(-1));
var btnRemove = $("<input />");
btnRemove.attr("type", "button");
btnRemove.attr("onclick", "Remove(this);");
btnRemove.addClass("btn btn-sm btn_row_remove")
btnRemove.val("x");
cell.append(btnRemove);
//Clear the TextBoxes.
//textBox_Order_No_cp.val("");
textBox_Product_id.val("");
textBox_Unit_price.val("");
textBox_Quantity.val("");
textBox_LineTotal.val("");
$('#btnAddProduct').attr("disabled", true);
});
function Remove(button) {
//Determine the reference of the Row using the Button.
var row = $(button).closest("TR");
var name = $("TD", row).eq(1).html();
//if (confirm("Do you want to delete: " + name)) {
// //Get the reference of the Table.
// var table = $("#tblProduct")[0];
// //Delete the Table row using it's Index.
// table.deleteRow(row[0].rowIndex);
//}
// if dirict delete with out msg
var table = $("#tblProduct")[0];
table.deleteRow(row[0].rowIndex);
};
$("body").on("click", "#btnTesting", function () {
//Loop through the Table rows and build a JSON array.
var DataMethod = new Array();
$("#tblProduct TBODY TR").each(function () {
var row = $(this);
var DataString = {};
DataString.MCombined_SalesDetail.Order_No_cp = row.find("TD").eq(0).html();
DataString.MCombined_SalesDetail.Product_id = row.find("TD").eq(1).html();
DataString.MCombined_SalesDetail.Unit_price = row.find("TD").eq(2).html();
DataString.MCombined_SalesDetail.Quantity = row.find("TD").eq(3).html();
DataString.MCombined_SalesDetail.LineTotal = row.find("TD").eq(4).html();
DataMethod.push(DataString);
alert("Check Array");
});
alert("Going To Ajax");
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Customer/Insert",
data: JSON.stringify(DataMethod),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
I have sent multiple models data to database successfully, but i face problems send multiple row data.

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

Cannot pass an HttpPostedFileBase from View to Action Method

In my view, I have an image element as follows:
<img id="ImageDisplay" class="img-thumbnail" width="280" height="280"
src="#Url.Action("GetFileFromHttpPostedFile", "Image", new { File = Model.File })"/>
When I debug my code, I can see that my Model.File is not null. But when I pass it to the action method, the action method receives the parameter as null. Here is my action method:
public FileContentResult GetFileFromHttpPostedFile(HttpPostedFileBase File)
{
byte[] imageData = new byte[File.ContentLength];
File.InputStream.Read(imageData, 0, File.ContentLength);
return GetFileFromData(imageData, File.ContentType);
}
Am I missing something? Can we not pass an HttpPostedFileBase to a method? Help please.
Edit:
I also have the following element in the view that allows the user to populate Model.File property:
<input type="file" name="File" id="File" onchange="loadFile(event)" />
loadFile(event) simply shows a preview of the picture on the view.
Edit 2: Here is the full code for the view:
#model MyProject.Models.ViewModels.ChangeProfileModel
#{
ViewBag.Title = "Change Your Profile";
}
<script>
$(document).ready(function () {
$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);
function updateCount() {
var cs = [500 - $(this).val().length];
$('#characters').text(cs);
}
});
var loadFile = function (event) {
var output = document.getElementById('ImageDisplay');
if (output != null) {
output.src = URL.createObjectURL(event.target.files[0]);
}
};
</script>
<h2>Change Your Profile Info</h2>
#using (Html.BeginForm("ChangeProfile", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
if (ViewBag.ChangesSaved == true)
{
<div class="alert alert-success">
Your changes have been saved successfully!
×
</div>
}
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.City, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Country, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Country, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Country, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Select an Image </label>
<div class="col-md-10">
<input type="file" name="File" id="File" onchange="loadFile(event)" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2"></label>
<div class="col-md-10">
#if (Model.File == null)
{
<img id="ImageDisplay" class="img-thumbnail" width="280" height="280"
src="#Url.Action("GetImageByUser", "Image", new { id = Model.Id })"/>
}
else
{
<img id="ImageDisplay" class="img-thumbnail" width="280" height="280"
src="#Url.Action("GetFileFromHttpPostedFile", "Image", new { File = Model.File })"/>
}
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.About, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextAreaFor(m => m.About, new { #class = "form-control", #rows = "5", #maxlength = 500 })
<span id="characters" style="color:#999;">500</span> <span style="color:#999;">characters left</span>
#Html.ValidationMessageFor(model => model.About, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
#Html.ActionLink("Cancel", "Index", "Manage", null, new { #class = "btn btn-default" })
</div>
</div>
</div>
}
In my HomeController, I have the following methods:
public ActionResult ChangeProfile()
{
var userId = User.Identity.GetUserId();
var loggedInUser = UserManager.FindById(userId);
ChangeProfileModel viewModel = new ChangeProfileModel
{
Id = userId,
City = loggedInUser.City,
Country = loggedInUser.Country,
About = loggedInUser.About
};
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ChangeProfile(ChangeProfileModel viewModel)
{
if (!ModelState.IsValid)
{
return View(viewModel);
}
var userId = User.Identity.GetUserId();
var loggedInUser = UserManager.FindById(userId);
byte[] imageData = null;
if (viewModel.File != null)
{
imageData = new byte[viewModel.File.ContentLength];
viewModel.File.InputStream.Read(imageData, 0, viewModel.File.ContentLength);
}
_aspNetUserRepository.EditUserInfo(userId, viewModel.City, viewModel.Country, viewModel.About,
imageData, (viewModel.File == null) ? null: viewModel.File.ContentType);
ViewBag.ChangesSaved = true;
return View(viewModel);
}
Lastly, here is my last relevant action method inside ImageController:
public FileContentResult GetFileFromHttpPostedFile(HttpPostedFileBase File)
{
byte[] imageData = new byte[File.ContentLength];
File.InputStream.Read(imageData, 0, File.ContentLength);
return GetFileFromData(imageData, File.ContentType);
}

Validate required model only

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

Client side validation not working on password

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

Resources