Validation is not working mvc - html

I just can`t find out what is wrong. I am trying no to allow setting null values to field, when user tries to do it, it must show message "*", and wait for him to set values, but it doesnot work and null values are successfully sent to an action.
Model :
public class CompanyMainInfoModel
{
public int CompanyId { get; set; }
[Required(ErrorMessage = "*")]
[Display(Name = "company_name", ResourceType = typeof(Localization))]
public string CompanyName { get; set; }
[Required(ErrorMessage = "*")]
[Display(Name = "company_address", ResourceType = typeof(Localization))]
public string CompanyAddress { get; set; }
[Required(ErrorMessage = "*")]
[Display(Name = "company_director", ResourceType = typeof(Localization))]
public string CompanyDirector { get; set; }
[Required(ErrorMessage = "*")]
[Display(Name = "company_phone", ResourceType = typeof(Localization))]
public string CompanyTelephoneNumber { get; set; }
}
Markup :
#model BTGHRM.Models.CompanyMainInfoModel
#{
Layout = "~/Views/Shared/_EmployeeMain.cshtml";
}
<head>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
</head>
<body>
<span class="content_h4">#Resources.Localization.company_info</span>
<br />
<br />
<div id="FormContainer">
#Html.Partial("Partial/_CompanyInfo", Model)
</div>
</body>
Partial Markup:
#model BTGHRM.Models.CompanyMainInfoModel
#using (Html.BeginForm("CompanyInfo", "Administration"))
{
<table>
<tr>
<td>#Html.LabelFor(m => m.CompanyName)</td>
<td>#Html.TextBoxFor(m => m.CompanyName)</td>
<td>#Html.ValidationMessageFor(m => m.CompanyName, "" , new { #class="text-danger"})</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.CompanyAddress)</td>
<td>#Html.TextBoxFor(m => m.CompanyAddress)</td>
<td>#Html.ValidationMessageFor(m => m.CompanyAddress, "", new { #class = "text-danger" })</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.CompanyDirector)</td>
<td>#Html.TextBoxFor(m => m.CompanyDirector)</td>
<td>#Html.ValidationMessageFor(m => m.CompanyDirector, "", new { #class = "text-danger" })</td>
</tr>
<tr>
<td>#Html.LabelFor(m => m.CompanyTelephoneNumber)</td>
<td>#Html.TextBoxFor(m => m.CompanyTelephoneNumber)</td>
<td>#Html.ValidationMessageFor(m => m.CompanyTelephoneNumber, "", new { #class = "text-danger" })</td>
</tr>
</table>
<input style="width:78px" type="submit" value=#Resources.Localization.save />
}
And despite [Required] it still allows me to set null values to any field.
What is wrong with my code?

You have to have unobtrusive scripts enabled in web config
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
Then you need to add
jquery
jquery.validate.js
jquery.validate.unobtrusive.js

You need to add "jquery.validate.js" and "jquery.validate.unobtrusive.js" in your View. Validation needs the above two files along with "Jquery.js". Hope this helps.

Related

How can make empty in each column while adding new rows in a table

I have a table with the column customer name, Address, Salary etc. But when I add the new row in the table using button btnUpdate , the previous row column value would be placed in the corresponding column of the new row . How can I make it empty column in the new row while adding it . Here is the code
public class EditHolidayEntVM
{
[Key]
public int id { get; set; }
public string Region { get; set; }
public int DepotNo { get; set; }
public int DepartmentID { get; set; }
public int EmployeeID { get; set; }
public decimal NetHrs { get; set; }
[DataType(DataType.Date, ErrorMessage = "Date only")]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public string FromDate { get; set; }
[DataType(DataType.Date, ErrorMessage = "Date only")]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime ToDate { get; set; }
public decimal HolidayEnt { get; set; }
}
Html
<table id="tblEntry" class="table table-striped">
<thead>
<tr>
<th>Date From</th>
<th>Date To</th>
<th>Net Hrs</th>
<th>Holiday Entitlement</th>
<th></th>
</tr>
</thead>edit
<tbody>
<tr>
<td>#Html.EditorFor(model => model.FromDate, new { htmlAttributes = new { #class = "form-control datepicker w-100" } })</td>
<td>#Html.EditorFor(model => model.ToDate, new { htmlAttributes = new { #class = "form-control datepicker w-100" } })</td>
<td>#Html.EditorFor(model => model.NetHrs, new { #id="netHrs", htmlAttributes = new { type = "number", #class = "form-control w-100" } })</td>
<td>#Html.EditorFor(model => model.HolidayEnt, new { htmlAttributes = new { #class = "form-control w-100", #readonly="readonly" } })</td>
<td>Delete</td>
</tr>
</tbody>
</table>
</div>
<br />
<div class="row padding-top-ten center-block">
<div class="col-md-4">
</div>
<div class="col-md-6">
<div class="col-sm-4">
<button type="button" id="btnUpdate" name="submitButton" value="DeleteAtt"
class="btn btn-primary form-control" onclick="AddNew();">
<i class="fa fa-save"></i><span class="padding-left-ten">Add New Row</span>
</button>
</div>
</div>
</div>
<script>
function AddNew() {
var newRow = $("#tblEntry tbody tr").first().clone();
var row = $("tbody").append(newRow);
netHrs.val("");
}
</script>
Seems you are cloning the full table with existing value. So to achieve your goal you have to copy new row with empty value. So the easiest way is to get last child element and make it value empty.
Implementation:
Just replace your AddNew function like below
<script>
function AddNew() {
var newRow = $("#tblEntry tbody tr").first().clone();
var row = $("tbody").append(newRow);
$("tbody tr:last-of-type td input").each(function (index, el) {
$(el).val("");
})
}
</script>
Output:
Hope it would resolve your problem.

When I add new row in the table, how can I set default value for all the decimal column in the new

I have some decimal columns in a row which are grouped under emphrs class. But when I add new row, inside the table, how can I set 0.00 as default value for all the column grouped under emphrs class
In my Model class EmpHrs.cs the column attribute
public decimal SundayNetHrs { get; set; }
public decimal MondayNetHrs { get; set; }
public decimal TuesdayNetHrs { get; set; }
public decimal WednesdayNetHrs { get; set; }
public decimal ThursdayNetHrs { get; set; }
public decimal FridayNetHrs { get; set; }
public decimal SaturdayNetHrs { get; set; }
In EmpHrs Html I have a table with EmpHrs column
<tbody>
<tr>
<td>#Html.TextBoxFor(model => model.FromDate, new { #class = "form-control date-input" })</td>
<td>#Html.TextBoxFor(model => model.ToDate, new { #class = "form-control date-input" })</td>
<td>#Html.EditorFor(model => model.SundayNetHrs, new { htmlAttributes = new { type = "number", #class = "form-control w-100 empHrs" } })</td>
<td>#Html.EditorFor(model => model.MondayNetHrs, new { htmlAttributes = new { type = "number", #class = "form-control w-100 empHrs" } })</td>
<td>#Html.EditorFor(model => model.TuesdayNetHrs, new { htmlAttributes = new { type = "number", #class = "form-control w-100 empHrs" } })</td>
<td>#Html.EditorFor(model => model.WednesdayNetHrs, new { htmlAttributes = new { type = "number", #class = "form-control w-100 empHrs" } })</td>
</tr>
</tbody>
<button type="button" id="btnUpdate" name="submitButton" value="DeleteAtt"
class="btn btn-primary form-control" onclick="AddNew();">
<i class="fa fa-save"></i><span class="padding-left-ten">Add New Row</span>
</button>
function AddNew() {
var clone = $("#tblEntry tr:last").clone().find('input').val('').end().insertAfter("#tblEntry tr:last");
$(clone).find(".date-input").datepicker({ format: 'dd/mm/yyyy', todayHighlight: true, date: new Date(), autoclose: true, todayBtn: 'linked' });
// Here All column under EmpHrs class should be set default value 0.00
}
You could try following way:
Model:
public class EmpHrs
{
[DataType(DataType.Date, ErrorMessage = "Date only")]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime FromDate { get; set; }
[DataType(DataType.Date, ErrorMessage = "Date only")]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime ToDate { get; set; }
public decimal SundayNetHrs { get; set; }
public decimal MondayNetHrs { get; set; }
public decimal TuesdayNetHrs { get; set; }
public decimal WednesdayNetHrs { get; set; }
public decimal ThursdayNetHrs { get; set; }
public decimal FridayNetHrs { get; set; }
public decimal SaturdayNetHrs { get; set; }
}
Controller:
public IActionResult SetDefaultValue()
{
var empHrs= new EmpHrs() { SundayNetHrs = 10, MondayNetHrs = 10, TuesdayNetHrs = 2, WednesdayNetHrs = 2, ThursdayNetHrs = 3, FridayNetHrs = 5, SaturdayNetHrs = 9 };
return View(empHrs);
}
Note: I am binding some default value on load. If you can skip it if required. On click we would set default value using javascript
as well in next part.
View:
#model EmpHrs
#{
ViewData["Title"] = "SetDefaultValue";
}
<table id="tblEntry" class="table table-striped">
<thead>
<tr>
<th>Date From</th>
<th>Date To</th>
<th>SundayNetHrs</th>
<th>MondayNetHrs</th>
<th>TuesdayNetHrs</th>
<th>WednesdayNetHrs</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>#Html.EditorFor(model => model.FromDate, new { #id = "FromDate", htmlAttributes = new { #class = "form-control datepicker w-100" } })</td>
<td>#Html.EditorFor(model => model.ToDate, new { #id = "ToDate", htmlAttributes = new { #class = "form-control datepicker w-100" } })</td>
<td>#Html.EditorFor(model => model.SundayNetHrs, new {#id = "SundayNetHrs", htmlAttributes = new { type = "number", #class = "form-control w-100 empHrs" } })</td>
<td>#Html.EditorFor(model => model.MondayNetHrs, new { #id = "MondayNetHrs", htmlAttributes = new { type = "number", #class = "form-control w-100 empHrs" } })</td>
<td>#Html.EditorFor(model => model.TuesdayNetHrs, new { #id = "TuesdayNetHrs", htmlAttributes = new { type = "number", #class = "form-control w-100 empHrs" } })</td>
<td>#Html.EditorFor(model => model.WednesdayNetHrs, new { #id = "WednesdayNetHrs", htmlAttributes = new { type = "number", #class = "form-control w-100 empHrs" } })</td>
</tr>
</tbody>
</table> <div class="row padding-top-ten center-block">
<div class="col-md-4">
</div>
<div class="col-md-6">
<div class="col-sm-4">
<button type="button" id="btnUpdate" name="submitButton" value="DeleteAtt"
class="btn btn-primary form-control" onclick="AddNew();">
<i class="fa fa-save"></i><span class="padding-left-ten">Add New Row</span>
</button>
</div>
</div>
</div>
Script:
<script>
function AddNew() {
// alert("Click");
var newRow = $("#tblEntry tbody tr").first().clone();
var row = $("tbody").append(newRow);
//Set Default value while adding new rows
var defaultValue = 0;
$("tbody tr:last-of-type td").find("input[id*='SundayNetHrs']").val(defaultValue.toFixed(2));
$("tbody tr:last-of-type td").find("input[id*='MondayNetHrs']").val(defaultValue.toFixed(2));
$("tbody tr:last-of-type td").find("input[id*='TuesdayNetHrs']").val(defaultValue.toFixed(2));
$("tbody tr:last-of-type td").find("input[id*='WednesdayNetHrs']").val(defaultValue.toFixed(2));
}
</script>
Note: Look at the tbody tr:last-of-type td selector here I am finding each inputbox and assigning a value into it. So just find
your expected input item and assign value using defaultValue with toFixed javascript method to set up decimal poniter.
Output:
Hope it would resolve your problem.
Use specific value:
public decimal SundayNetHrs { get; set; }=0.00;
public decimal MondayNetHrs { get; set; }=0.00;
public decimal TuesdayNetHrs { get; set; }=0.00;
public decimal WednesdayNetHrs { get; set; }=0.00;
public decimal ThursdayNetHrs { get; set; }=0.00;
public decimal FridayNetHrs { get; set; }=0.00;
public decimal SaturdayNetHrs { get; set; }=0.00;

MVC, Razor - Submitting form (inside #if) gives empty object in post

I am trying to save some changes to a database.
The view gets a Model, and should be able to make changes and have them saved. However, when i submit the form, the ContactInfo parameter in the post method is not null, but all the properties are.
I'm using MVC5 with Razor. the script is in a seperate .ts-file
In controller:
[HttpPost]
public bool SaveInfoChanges(ContactInfo editedContactInfo)
{
// Save data
return true;
}
Script:
export function saveInfoChanges() {
$("#EditContactInfoForm").submit();
};
HTML:
#if (true)
{
#using (Html.BeginForm("SaveInfoChanges", "ContactInfoBox", FormMethod.Post, new { id = "EditContactInfoForm" }))
}
<table>
#Html.HiddenFor(model => model.Name)
#Html.HiddenFor(model => model.Address1)
#Html.HiddenFor(model => model.Address2)
#Html.HiddenFor(model => model.ZipAndCity)
#Html.HiddenFor(model => model.Country)
<tr>
<td>test</td>
<td>
#Html.TextBoxFor(model => model.Address3, new { id = "ContactTypeInput", placeholder = "", style = "width:300px" })
</td>
</tr>
</table>
}
}
Model:
public class ContactInfo
{
public string ContactInfoBoxHeaderText { get; set; }
public string Name { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Address3 { get; set; }
public string ZipAndCity { get; set; }
public string Country { get; set; }
}
I can't think of more relevant information to give, but please don't hesitate to ask.
Thanks in advance!
Removing the #if solved the problem. I just need to find another way to hide/show the elements.

Pass variable to strongly typed form from different view

I'm having a little trouble passing url variables to a form on a separate view. Basically I have a 'HomeController' which has a 'Contact' action and view, and a 'SalesController' which has an action and a view called 'View'.
On the view called 'View' (confusing I know), I have an action link like so:
<a href="#Url.Action("Contact", "Home", new { pid = Model.Property[0].Pid, type = "Viewing"})" class="detailsBtn">
As you can see, this is passing two variables of 'pid' and 'type' to the 'Contact' action of the 'HomeController'. The contact returns a strongly typed view with the following model being used.
public class ContactModel
{
[Required]
[DataType(DataType.Text)]
public string FullName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
[Required]
[DataType(DataType.PhoneNumber)]
[Phone(ErrorMessage = "Invalid Phone Number")]
public string Telephone { get; set; }
[DataType(DataType.Text)]
public string Address { get; set; }
[Required]
[DataType(DataType.Text)]
public string Subject { get; set; }
[Required]
[DataType(DataType.Text)]
public string Message { get; set; }
}}
Here's the Contact view:
#using (Html.BeginForm())
{
<div class="formField">
<span class="label">Full Name *</span><br />
#Html.TextBoxFor(Model => Model.FullName, new { #class = "txtContact" })
#Html.ValidationMessageFor(Model => Model.FullName, "Full enter your full name")<br/>
</div>
<div class="formField">
<span class="label">Email Address *</span><br />
#Html.TextBoxFor(Model => Model.Email, new { #class = "txtContact" })
#Html.ValidationMessageFor(Model => Model.Email, "Please ensure that a valid email is entered.")<br/>
</div>
<div class="formField">
<span class="label">Telephone *</span><br />
#Html.TextBoxFor(Model => Model.Telephone, new { #class = "txtContact" })
#Html.ValidationMessageFor(Model => Model.Telephone, "Please enter a valid telephone number")<br/>
</div>
<div class="formField">
<span class="label">Property Address (optional)</span><br />
#Html.TextBoxFor(Model => Model.Address, new {#class = "txtContact" })<br />
</div>
<div class="formField">
<span class="label">Subject *</span><br />
#if (ViewBag.Pid != null) {
#Html.TextBoxFor(Model => Model.Subject, new {#class = "txtContact" })
} else {
#Html.TextBoxFor(Model => Model.Subject, new { #class = "txtContact" })
}
#Html.ValidationMessageFor(Model => Model.Subject, "Please enter a subject")<br/>
</div>
<div class="formField">
<span class="label">Message *</span><br />
#Html.TextAreaFor(Model => Model.Message, new { #class = "txtContact" })
#Html.ValidationMessageFor(Model => Model.Message, "Please enter a message")<br/>
</div>
<input type="submit" class="contact-btn" value="Send" />
}
I simply need to know the best way for me to add the 'pid' and 'type' variables passed to the Contact Action from the Action link in the Sales Controller as values for my text boxes in the contact form.
You can always extend your Model to include a PID and Type property.
In your form you could just enter #Html.HiddenFor(Model => model.Pid) and #Html.HiddenFor(Model => model.Type) (or #Html.DisplayFor if you want them visible)
If you didn't want to do that, you could put your PID and Type values into ViewBag or ViewData from the Action, and then put these values into form fields in your view.
Edit:
If you would like the Pid and Type to be part of your strongly typed view, you can change your model to be like the following:
public class ContactModel
{
//all your other properties...
public string ContactType { get; set; }
public string Pid { get; set; }
}
Then in your Contact action, you can:
var model = new ContactModel() { ContactType = type, Pid = pid };
return View(model);

Bind data from db to dropdownlist + ASP.NET MVC

I have a question about using a dropdownlist in ASP.net MVC.
This is my situation:
Create view:
#using (Html.BeginForm("Create", "Deliverable", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>EventViewModel</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Title)
#Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Thumbnail)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Thumbnail, new { type = "file" })
#Html.ValidationMessageFor(model => model.Thumbnail)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Image)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Image , new {type="file"})
#Html.ValidationMessageFor(model => model.Image)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.VideoUrl)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.VideoUrl)
#Html.ValidationMessageFor(model => model.VideoUrl)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.VideoUrl)
</div>
<div class="editor-field">
#Html.ValidationMessageFor(model => model.VideoUrl)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
After the 'VideoURL' I would like to have a Dropdownlist with values that are stored in my database. Most of the tutorials that I find don't bind the values in the dropdownlist to the database.
I insert the values in my db in my backoffice so I can't insert them in frontoffice...
This is my Controller:
public ActionResult Create(DeliverableViewModel model)
{
var afstudeerrichtingen = (repository.GetAfstudeerrichtingen()).ToList();
if (ModelState.IsValid)
{
try
{
MemoryStream target = new MemoryStream();
model.Image.InputStream.CopyTo(target);
byte[] data = target.ToArray();
model.Thumbnail.InputStream.CopyTo(target);
byte[] datatwo = target.ToArray();
users usr = userrepo.FindByUsername(User.Identity.Name);
model.UsernameID = usr.user_id;
repository.AddDeliverable(model.Title, model.Description, model.UsernameID, data, datatwo, model.VideoUrl, model.Afstudeerrichting);
}
catch (ArgumentException ae)
{
ModelState.AddModelError("", ae.Message);
}
return RedirectToAction("Index");
}
return View(model);
}
In sent the values to my repository where I save it in my database.
This is my DeliverableViewModel:
public class DeliverableViewModel
{
[Required]
[Display(Name = "Title")]
public string Title { get; set; }
[Required]
[Display(Name = "Description")]
public string Description { get; set; }
[Required]
[Display(Name = "Thumbnail")]
public HttpPostedFileBase Thumbnail { get; set; }
[Required]
[Display(Name = "Image")]
public HttpPostedFileBase Image { get; set; }
[Required]
[Display(Name = "VideoUrl")]
public string VideoUrl { get; set; }
[Required]
[Display(Name = "AfstudeerrichtingID")]
public int AfstudeerrichtingID { get; set; }
[Required]
[Display(Name = "Afstudeerrichting")]
public IEnumerable<SelectListItem> Items { get; set; }
public long UsernameID { get; set; }
}
Does anyone know what I have to add in my view & controller to make this work?
The values are in my tabel "Afstudeerrichtingen" in my mysql database
- afstuddeerichting_id
- afstudeerrichting_name
Add a dropdownlist in your view:
#Html.DropDownListFor(model => model.AfstudeerrichtingID,
new SelectList(ViewBag.Richtingen,
"AfstudeerrichtingId", "AfstudeerrichtingName"))
Add your Afstudeerrichting collection to the ViewBag in the controller:
ViewBag.Richtingen = afstudeerrichtingen;
Assuming that that collection contains the properties AfstudeerrichtingId and AfstudeerrichtingName, as used in the view.
Another thing to do is change your AfstudeerrichtingID to string, and translate it to/from int in your repository class.