Bootstrap 3 Eonasdan DatetimePicker Stops submiting Form - asp.net-mvc

I have added Bootstrap 3 eonasdan-datetimepicker. When I Select Datetimepicker
it gives focus to that particular Datetimepicker
and when i click on submit button, Submit button prevents submitting form and
opens datetimepicker-dialog as if it becomes part of datetimepicker
My ViewModel:
[Display(Name = "From")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime From { get; set; }
[Display(Name = "To")]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime To { get; set; }
And View Is:
<div class="form-group">
#Html.LabelFor(model => model.From, htmlAttributes: new { #class = "control-label col-lg-4 col-md-4" })
<div class="col-lg-6 col-md-6">
#Html.TextBoxFor(model => model.From, new { #class = "form-control datetime"})
#Html.ValidationMessageFor(model => model.From, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.To, htmlAttributes: new { #class = "control-label col-lg-4 col-md-4" })
<div class="col-lg-6 col-md-6">
#Html.TextBoxFor(model => model.To, new { #class = "form-control datetime" })
#Html.ValidationMessageFor(model => model.To, "", new { #class = "text-danger" })
</div>
</div>
#section Styles{
#Styles.Render("~/Content/jqueryui")
#Styles.Render("~/Content/datetimepicker")
}
#section Scripts{
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/datetimepicker")
<script type="text/javascript">
$(function () {
//setting datetime picker.
$('#From').datetimepicker({ format: 'DD/MM/YYYY'});
$('#To').datetimepicker({
useCurrent: false, //Important! See issue #1075
format: 'DD/MM/YYYY'
});
$("#From").on("dp.change", function (e) {
$('#To').data("DateTimePicker").minDate(e.date);
});
$("#To").on("dp.change", function (e) {
$('#From').data("DateTimePicker").maxDate(e.date);
});
});
</script>
}

Related

How Send Multiple Rows by using multiple models in 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.

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

model post back with html attribute

I am having an issue with getting the value back in my ViewModel after a postback using a JQuery datepicker. The post back has the correct date with the form group StartDate that does not have a new htmlAttribute attached to the EditorFor. The StopDate does not post back the selected date due to the htmlAttribute. I would prefer not to use a hidden field to send back the data since I know this should work. Anybody have any suggestions?
<div class="form-group" id="StartDate">
#Html.LabelFor(model => model.StartDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.reportTimeEntries[0].StartDate, "","StartDate" )
#Html.ValidationMessageFor(model => model.StartDate, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.StartDate)
</div>
</div>
<div class="form-group" id="StopDate">
#Html.LabelFor(model => model.StopDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.reportTimeEntries[0].StopDate, new { htmlAttributes = new { #class = "form-control date" } })
#Html.ValidationMessageFor(model => model.StopDate, "", new { #class = "text-danger" })
</div>
</div>
$('#StartDate .date').datepicker({
'format': 'mm/dd/yyyy',
'autoclose': true
});
$('#StopDate .date').datepicker({
'format': 'mm/dd/yyyy',
'autoclose': true
});
UPDATE
So it seems that this has worked by adding this to my ViewModel. The 'Nullable' section seems to allow the date to be posted back.
ViewModel
[DataType(DataType.DateTime)]
[Display(Name = "Stop Date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> StopDate { get; set; }
View
<div class="form-group" id="StopDate">
#Html.LabelFor(model => model.StopDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.reportTimeEntries[0].StopDate, "","StopDate",new { htmlAttributes = new { #class = "form-control date" } })
#Html.ValidationMessageFor(model => model.StopDate, "", new { #class = "text-danger" })
</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; }

Multiple models for one view not working

I have a Customer model and a Project model that I made into a Partial View.
I basically have a class and the two models that I'm using for the View are inside the main class.
The DataAnnotations are working just fine for both models.
When I hit the submit button and post back, the ViewModel that I'm using is null for the CustomerDTO & ProjectDTO models. In other words, the variable customerProject is null for both classes.
I think it must have something to do with the model binding.
I would appreciate very much if someone can point out what I'm doing wrong.
Note that if I just use one class without wrapping the sub-classes inside the superclass, the "customer" object is populated.
public ActionResult CreateCust(CustomerDTO customer)
This one class is defined as follows:
using Models.Models;
namespace Models.ViewModels.Customers
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class CustomerDTO
{
[Key]
[ScaffoldColumn(true)]
[Display(Name = "ID")]
public short CustomerID { get; set; }
[Required]
[StringLength(50)]
public string UserName { get; set; }
[Required]
[StringLength(50)]
[EmailAddress]
public string Email { get; set; }
[StringLength(50)]
public string Company { get; set; }
[StringLength(50)]
public string FirstName { get; set; }
[StringLength(50)]
public string LastName { get; set; }
[StringLength(50)]
public string Address1 { get; set; }
[StringLength(50)]
public string Address2 { get; set; }
[StringLength(50)]
public string City { get; set; }
[StringLength(2)]
public string State { get; set; }
[StringLength(10)]
[DataType(DataType.PostalCode)]
[RegularExpression(#"^\d{5}(-\d{4})?$")]
public string Zip { get; set; }
[StringLength(12)]
[DataType(DataType.PhoneNumber)]
[RegularExpression(#"^\s*([\(]?)\[?\s*\d{3}\s*\]?[\)]?\s*[\-]?[\.]?\s*\d{3}\s*[\-]?[\.]?\s*\d{4}$")]
public string HomePhone { get; set; }
[StringLength(12)]
[DataType(DataType.PhoneNumber)]
[RegularExpression(#"^\s*([\(]?)\[?\s*\d{3}\s*\]?[\)]?\s*[\-]?[\.]?\s*\d{3}\s*[\-]?[\.]?\s*\d{4}$")]
public string CellPhone { get; set; }
[StringLength(100)]
[DataType(DataType.Url)]
public string Website { get; set; }
[StringLength(50)]
[DataType(DataType.Url)]
public string IMAddress { get; set; }
[DataType(DataType.DateTime)]
[Display(Name = "Created")]
public DateTime CreatedDate { get; set; }
[DataType(DataType.DateTime)]
[Display(Name = "Updated")]
public DateTime? UpdatedDate { get; set; }
public virtual ICollection<Project> Projects { get; set; }
}
}
Here is my model (Please use your favorite viewer to view the image to enlarge it).
My Main View is defined as follows:
#model Models.ViewModels.Customers.CustomerDTO
#{
ViewBag.Title = "Create Customer & Project";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
#using (Html.BeginForm("CreateCustProj", "Home", FormMethod.Post, new { #id = "frm1", #class = "form-horizontal" }))
{
<div class="body-content">
<h4>Customer/Project</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<fieldset>
<legend>Customer</legend>
<div class="form-group">
<div class="col-lg-offset-1 col-md-offset-1 col-sm-offset-1 col-xs-offset-1 col-lg-11 col-md-11 col-sm-11 col-xs-11">
#Html.EditorFor(model => model.UserName, new { htmlAttributes = new { #class = "form-control", #placeholder = "UserName" } })
#Html.ValidationMessageFor(model => model.UserName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-1 col-md-offset-1 col-sm-offset-1 col-xs-offset-1 col-lg-11 col-md-11 col-sm-11 col-xs-11">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control", #placeholder = "Email" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-1 col-md-offset-1 col-sm-offset-1 col-xs-offset-1 col-lg-11 col-md-11 col-sm-11 col-xs-11">
#Html.EditorFor(model => model.Company, new { htmlAttributes = new { #class = "form-control", #placeholder = "Company" } })
#Html.ValidationMessageFor(model => model.Company, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-1 col-md-offset-1 col-sm-offset-1 col-xs-offset-1 col-lg-5 col-md-5 col-sm-5 col-xs-5">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control", #placeholder = "First Name" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
<div class="col-lg-5 col-md-5 col-sm-5 col-xs-5">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control", #placeholder = "Last Name" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-1 col-md-offset-1 col-sm-offset-1 col-xs-offset-1 col-lg-11 col-md-11 col-sm-11 col-xs-11">
#Html.EditorFor(model => model.Address1, new { htmlAttributes = new { #class = "form-control", #placeholder = "Address1" } })
#Html.ValidationMessageFor(model => model.Address1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-1 col-md-offset-1 col-sm-offset-1 col-xs-offset-1 col-lg-11 col-md-11 col-sm-11 col-xs-11">
#Html.EditorFor(model => model.Address2, new { htmlAttributes = new { #class = "form-control", #placeholder = "Address2" } })
#Html.ValidationMessageFor(model => model.Address2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-1 col-md-offset-1 col-sm-offset-1 col-xs-offset-1 col-lg-6 col-md-6 col-sm-6 col-xs-6">
#Html.EditorFor(model => model.City, new { htmlAttributes = new { #class = "form-control", #placeholder = "City" } })
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
<div class="col-md-3 col-sm-3 col-xs-3">
#Html.EditorFor(model => model.State, new { htmlAttributes = new { #class = "form-control", #placeholder = "State" } })
#Html.ValidationMessageFor(model => model.State, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-1 col-md-offset-1 col-sm-offset-1 col-xs-offset-1 col-lg-3 col-md-3 col-sm-3 col-xs-3">
#Html.EditorFor(model => model.Zip, new { htmlAttributes = new { #class = "form-control", #placeholder = "Zip" } })
#Html.ValidationMessageFor(model => model.Zip, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-1 col-md-offset-1 col-sm-offset-1 col-xs-offset-1 col-lg-5 col-md-5 col-sm-5 col-xs-5">
#Html.EditorFor(model => model.HomePhone, new { htmlAttributes = new { #class = "form-control", #placeholder = "Home Phone" } })
#Html.ValidationMessageFor(model => model.HomePhone, "", new { #class = "text-danger" })
</div>
<div class="col-lg-5 col-md-5 col-sm-5 col-xs-5">
#Html.EditorFor(model => model.CellPhone, new { htmlAttributes = new { #class = "form-control", #placeholder = "Cell Phone" } })
#Html.ValidationMessageFor(model => model.CellPhone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-1 col-md-offset-1 col-sm-offset-1 col-xs-offset-1 col-lg-5 col-md-5 col-sm-5 col-xs-5">
#Html.EditorFor(model => model.Website, new { htmlAttributes = new { #class = "form-control", #placeholder = "Website" } })
#Html.ValidationMessageFor(model => model.Website, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-1 col-md-offset-1 col-sm-offset-1 col-xs-offset-1 col-lg-5 col-md-5 col-sm-5 col-xs-5">
#Html.EditorFor(model => model.IMAddress, new { htmlAttributes = new { #class = "form-control", #placeholder = "IM Address" } })
#Html.ValidationMessageFor(model => model.IMAddress, "", new { #class = "text-danger" })
</div>
</div>
</fieldset>
<fieldset>
<legend>Project</legend>
#Html.Partial("_Projects", Model)
</fieldset>
<div class="form-group">
<div>
<button type="submit" id="btnCustomerProjectCreate" class="btn btn-primary col-offset-2"><span class="glyphicon glyphicon-save"></span>Create</button>
</div>
</div>
</div>
}
My Partial View (noted above as #Html.Partial) is as follows:
#model Models.ViewModels.Projects.ProjectDTO
<div class="form-group">
<div class="col-lg-offset-1 col-md-offset-1 col-sm-offset-1 col-xs-offset-1 col-lg-11 col-md-11 col-sm-11 col-xs-11">
#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">
<div class="col-lg-offset-1 col-md-offset-1 col-sm-offset-1 col-xs-offset-1 col-lg-11 col-md-11 col-sm-11 col-xs-11">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-1 col-md-offset-1 col-sm-offset-1 col-xs-offset-1 col-lg-11 col-md-11 col-sm-11 col-xs-11">
#Html.DropDownListFor(model => model.CategoryID, new SelectList(ViewBag.Categories, "CategoryID", "Description", ViewBag.CategoryID == null ? null : ViewBag.CategoryID), "-- Select Category --", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CategoryID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-1 col-md-offset-1 col-sm-offset-1 col-xs-offset-1 col-lg-11 col-md-11 col-sm-11 col-xs-11">
#Html.DropDownListFor(model => model.PriorityID, new SelectList(ViewBag.Priorities, "PriorityID", "Description", ViewBag.PriorityID == null ? null : ViewBag.Priority), "-- Select Priority --", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PriorityID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-1 col-md-offset-1 col-sm-offset-1 col-xs-offset-1 col-lg-11 col-md-11 col-sm-11 col-xs-11">
#Html.DropDownListFor(model => model.StatusID, new SelectList(ViewBag.Statuses, "StatusID", "Description", ViewBag.StatusID == null ? null : ViewBag.StatusID), "-- Select Status --", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StatusID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-1 col-md-offset-1 col-sm-offset-1 col-xs-offset-1 col-lg-11 col-md-11 col-sm-11 col-xs-11">
#Html.EditorFor(model => model.Quote, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Quote, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-1 col-md-offset-1 col-sm-offset-1 col-xs-offset-1 col-lg-11 col-md-11 col-sm-11 col-xs-11">
#Html.EditorFor(model => model.Notes, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Notes, "", new { #class = "text-danger" })
</div>
</div>
I think you are confusing yourself of what to pass where and how it will be rendered.
You have two models
CustomerDTO
ProjectDTO
You are Creating a ViewModel and passing it to View that is of type CustomerDTO. When you Pass same model to partial #Html.Partial("_Projects", Model) , You are passing CustomerDTO. However, partial view is expecting to recieve ProjectDTO. Means You should pass ProjectsDTO.
Now I can see that You have
public virtual ICollection Projects { get; set; }
set in there, I am assuming Projects Contains ProjectDTO model in it by looking at your namespace declaration.
Pass ProjectDTO model with foreach loop using
#foreach(var item in Model.Projects)
{
#Html.Partial(item.ProjectDTO)
}
This will work. However, this is not best practice. You should get ICollection and use DisplayTemplate to Render your data.
Please post, your ProjectsDTO model and also post what is expected output that you want so that We can answer specifically of where are things going wrong,
Update
I think now I understand where things are going Wrong. I will try to keep it simple while I explain.
You said , Your models are coming back as null. There could be three reasons for that to happen.
You never Instantiated your model. Do it by (CustomerDTO cDTO = new CustomerDTO()
Get it from somewhere , for example CustomerDTO cDTO = getCustomerDTO() where getCustomerDTO() function returs CustomerDTO model.
Even though you had a Model with you , you never passed it to View. You can do this in Action something like follow.
Public ActionResult ShowCustomer()
{
CustomerDTO cDTO = new CustomerDTO();
return View("ViewName" , cDTO);
}
Moving to Second issue where You want to have a superClass that contains Multiple Classes.
You have DTO are your DomainModels, whose job is to get data from Database, I think they are doing Their Job. NOw If Both of those Domain models needs to go to View, you need to Create ViewModel that will look something like this,
public class DTOViewModel
{
public CustomerDTO Customer {get ; set ;}
public ProjectsDTO Projects {get; set;}
}
Then you can Create Action that will look something like following,
public ActionResult DTOViews()
{
DTOViewModel model = new DTOViewModel();
model.Customer = getCustomer();
model.Projects = getProjects();
return View("YourView" , model); //Make sure ViewName exist in Respective Folder.
}
Then in View You may have following;
#model namespace.DTOViewModel
<h2> This is your main View. </h2>
#Html.Partial("_CustomerPartial" , model.Customer )
#Html.Partial("_ProjectPartial" , model.Projects )
Hope this helps.
Check the generated Html of the helpers. You need the name of the form elements to be something like "CustomerProjectDto.CustomerDto.Description". With Partials I thing you get "Description".
Try to use your own Editor Templates that create the right html for complex nodells.
Check this article to read about it. https://lostechies.com/jimmybogard/2011/09/07/building-forms-for-deep-view-model-graphs-in-asp-net-mvc/

Resources