Field required attribute acidentially invoked but clicking a button - asp.net-mvc

I have these fields, and I implemented required attribute on them.
#using (Html.BeginForm("Edit", "ChannelsGrid", FormMethod.Post, new {name = "channelForm", #class = "channelForm", #enctype = "multipart/form-data"}))
{
<div class="form-group">
#Html.HiddenFor(model => Model.Id)
<div class="row">
<div class="col-md-6">
#Html.Label("Part/Location", new {#class = "control-label"})
#Html.TextBox("PartLocation", null, new { #class = "form-control", #required = "required" })
</div>
<div class="col-md-6">
#Html.Label("Index", new {#class = "control-label"})
#Html.TextBox("Index", null, new {#class = "form-control"})
</div>
</div>
<div class="row">
<div class="col-md-6">
#Html.Label("Measurement", new {#class = "control-label"})
#Html.DropDownListFor(model => model.Measurement, (SelectList)ViewBag.Measurements, "-- Select Measurement --", new { #class = "form-control", #required = "required" })
</div>
<div class="col-md-6">
#Html.Label("Location", new {#class = "control-label"})
#Html.DropDownList("Directions", ViewBag.DirectionTypes as List<SelectListItem>, "-- Select Direction --", new { #class = "form-control", #required = "required" })
</div>
</div>
<div class="row">
<div class="col-md-6">
#Html.LabelFor(model => model.ChannelGroupId, new {#class = "control-label"})
#Html.DropDownListFor(x => x.ChannelGroupId, Model.ChannelGroups, "Select Channel Group", new {#class = "form-control"})
#Html.ValidationMessageFor(model => model.ChannelGroupId)
</div>
<div class="col-md-3">
<label class="control-label"></label>
<a href="#" id="addChannelGroup" class="form-control" style="border: none">
<i class="fa fa-plus-circle">Add Group</i>
</a>
</div>
<div class="col-md-3">
<label class="control-label"></label>
<a href="#" id="addMeasurement" class="form-control" style="border: none">
<i class="fa fa-plus-circle">Add Measurement</i>
</a>
</div>
</div>
<br/>
<div class="row">
<div class="col-md-6">
#Html.Label("Channel name: ", new {id = "channelName", #class = "control-label"})
</div>
<div class="col-md-6">
#Html.TextBox("HiddenTextBox", null, new {#class = "hidden"})
<div class="col-md-1">
#Html.TextBoxFor(a => a.Name, new {#class = "hidden"})
</div>
</div>
</div>
</div>
<div class="row" id="pnlAddChannelGroupName" style="display: none">
<div class="col-md-6">
<label class="control-label">Channel Group Name :</label>
<input type="text" id="ChannelGroupName" name="ChannelGroupName" class="form-control"/>
<input type="button" value="Cancel" id="channelGroupButton" />
#*<button id="channelGroupButton">Cancel</button>*#
</div>
</div>
<div class="row" id="pnlMeasurement" style="display: none">
<div class="col-md-6">
#Html.Label("Measurement :", new {#class = "control-label"})
#Html.TextBox("MeasurementName", null, new {#class = "form-control"})
<input type="button" value="Cancel" id="measurementButton" />
#*<button id="measurementButton">Cancel</button>*#
</div>
</div>
}
I also have two buttons which are used to toggle other textboxes in this form. Here is the code.
<div class="row" id="pnlAddChannelGroupName" style="display: none">
<div class="col-md-6">
<label class="control-label">Channel Group Name :</label>
<input type="text" id="ChannelGroupName" name="ChannelGroupName" class="form-control"/>
<button id="channelGroupButton">Cancel</button>
</div>
</div>
<div class="row" id="pnlMeasurement" style="display: none">
<div class="col-md-6">
#Html.Label("Measurement :", new {#class = "control-label"})
#Html.TextBox("MeasurementName", null, new {#class = "form-control"})
<button id="measurementButton">Cancel</button>
</div>
</div>
The problem is whenever I click these two Cancel buttons in that field, the three fields seems to be invoked and there is brown border around the textbox dropdownlist. I guess these field have been submitted. But I thought I use button element instead of type button of an input so I can eliminate the submitting action of the button, right? Any clues? And how can I click these Cancel buttons withouts invoking validation in these other field?
Edited: I changed all the buttons to input type="button" and the validation of these other field dissapeared. Can someone explain?
This is my viewmodel:
namespace CrashTestScheduler.Entity.ViewModel
{
public class ChannelViewModel
{
public int Id { get; set; }
//[Display(Name = "Name")]
//[Required(ErrorMessage = "Please specify the channel name.")]
public string Name { get; set; }
public string Description { get; set; }
public string ChannelGroupName { get; set; }
public string MeasurementName { get; set; }
[Required(ErrorMessage = "Please select a channel group.")]
public int ChannelGroupId { get; set; }
public IEnumerable<SelectListItem> ChannelGroups { get; set; }
//[Required]
public string Measurement { get; set; }
}
}

The reason your form is submitting when clicking buttons is that the default action for a <button> element is type="submit" (refer documentation). You need to explicitly set the type attribute
<button type="button" ....>
However you have numerous issues with your approach.
By removing the [Required] attributes and using the required =
"required" html attribute, you now need to include manual
validation on the controller (never trust the user!)
Your mixing up Razor and manual html in the view, potentially
creating problems for model binding. Some of your label elements
wont work. (e.g. the first one is associated with a control named
"Part/Location" but there is no control named "Part/Location").
The user interface where your force users to click buttons to swap
between textboxes and dropdown lists is confusing and a sure way to
lose customers. Instead you should use an autocomplete control such
as jQuery Autocomplete which allows selection from a list or
direct text entry.
Your view model should contain validation attributes for its properties and can be simplified to
public class ChannelViewModel
{
public int Id { get; set; }
[Display(Name = "Part/Location")]
[Required]
public string PartLocation { get; set; }
public string Index { get; set; }
[Required]
public string Measurement { get; set; }
[Required]
[Display(Name = "Location")]
public int Direction { get; set; }
.... // other properties
public SelectList DirectionList { get; set; }
}
View
#Html.HiddenFor(model => Model.Id)
#Html.LabelFor(m => m.PartLocation, new {#class = "control-label"})
#Html.TextBoxFor(m => m.PartLocation, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.PartLocation)
#Html.LabelFor(m => m.Index, new {#class = "control-label"})
#Html.TextBoxFor(m => m.Index, new {#class = "form-control"})
#Html.LabelFor(m => m.Measurement, new {#class = "control-label"})
#Html.TextBoxFor(m => m.Measurement, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Measurement)
#Html.LabelFor(m => m.Direction, new {#class = "control-label"})
#Html.DropDownListFor(m => m.Direction, Model.DirectionList, "-- Select Direction --", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Direction)
.... // more controls
The attach the autocomplete to $(#Measurement).autocomplete({...
This will give you client and server side validation out of the box, and a better user interface.

Related

How to use SweetAlert before return RedirectToAction by Form Post?

Model
public class Company{
[StringLength(30)]
public string Name{ get; set; }
[StringLength(15)]
public string RegisterNo { get; set; }
}
View
<form id="form" method="post" action="/Controller/Save" style="font-size:13px;">
<div class="row pb-3">
<div class="form-row">
<div class="col-md-3">
<div class="position-relative form-group">
<label class="">Company Name</label> #Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control", #maxlength = "30" } })
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-6">
<div class="position-relative form-group">
<label class="">Reg No</label> #Html.EditorFor(model => model.RegisterNo, new { htmlAttributes = new { #class = "form-control", #maxlength = "15" } })
</div>
</div>
</div>
</div>
</form>
<button name="submit">Save</button>
Controller
public ActionResult Save(Company CompDet){
string Name = CompDet.Name;
string RegNo = CompDet.RegisterNo;
//then Connect DB and Save DB
//HOW TO use SweetAlert before, return RedirectToAction
}
I'm currently using, return RedirectToAction Only.
How to add SweetAlert before RedirectToAction?
Using Ajax Post or Form Post?
Possible that using Ajax & Form Post Together?
After Saving -> Show Sweetalert success -> return redirectToAction
I'm still at the learning level. Please Help.
Thank You

SelectListItem properties in view model are not passed back from view to controller

I have this View Model:
public class UserViewModel
{
public string ID { get; set; }
[Required]
[Display(Name = "Nombre")]
public string Nombre { get; set; }
[Required]
[Display(Name = "Login")]
public string Login { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Contraseña")]
public string Password { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "E-mail")]
public string Email { get; set; }
[DataType(DataType.PhoneNumber)]
[Display(Name = "Teléfono")]
public string PhoneNumber { get; set; }
[Display(Name = "Ciudad")]
public System.Web.Mvc.SelectListItem City { get; set; }
[Display(Name = "Empresas")]
public IEnumerable<System.Web.Mvc.SelectListItem> Empresas { get; set; }
[Required]
[Display(Name = "Perfil")]
public string Role { get; set; }
[Display(Name = "Está Vigente")]
public bool Vigente { get; set; }
}
the problem I am having is that when I select something in City and Empresas in the form (they are both SELECT fields), they are not passed to controller in UserViewModel parameter:
public JsonResult EditUser(UserViewModel model)
{
.....
}
Only other properties are passed.
What is the right way to manage this?
EDIT:
this is part of the view:
#using (Html.BeginForm("EditUser", "Account", new { area = "Security" }, FormMethod.Post, new { #class = "form-horizontal form-label-left", role = "form", novalidate = "novalidate", id = "frmUsuario" }))
{
var id = Model == null ? String.Empty : Model.ID;
<div class="errores col-md-12 col-sm-12 col-xs-12" style="display: none">
<div class='validation-summary-errors alert alert-danger alert-white rounded' data-valmsg-summary="true">
<div class="icon">
<i class="fa fa-times-circle"></i>
</div>
<p>Debe completar los campos marcados en forma correcta.</p>
</div>
</div>
#Html.AntiForgeryToken();
<input type="hidden" value="#id" id="id" name="id" />
<div class="item col-md-12 col-sm-12 col-xs-12 form-group has-feedback">
#Html.TextBoxFor(m => m.Nombre, new { #class = "form-control has-feedback-left", placeholder = "Nombre", required = "required" })
<span class="fa fa-user form-control-feedback left" aria-hidden="true"></span>
</div>
<div class="item col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
#Html.TextBoxFor(m => m.Login, new { #class = "form-control has-feedback-left", placeholder = "Login", required = "required" })
<span class="fa fa-sign-in form-control-feedback left" aria-hidden="true"></span>
</div>
<div class="item col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
#{
//var requerido = String.IsNullOrEmpty(userId) ? "required" : String.Empty;
var requerido = Model == null || String.IsNullOrEmpty(Model.ID);
object htmlAttributes = null;
if (requerido)
{
htmlAttributes = new { #class = "form-control has-feedback-left", placeholder = "Contraseña", required = "required" };
}
else
{
htmlAttributes = new { #class = "form-control has-feedback-left", placeholder = "Contraseña" };
}
}
<!-- Para evitar que los password managers llenen los campos -->
<input type="text" id="hidUser" style="display: none" />
<!-- Para evitar que los password managers llenen los campos -->
<input type="password" id="hidPassword" style="display: none" />
#Html.PasswordFor(m => m.Password, htmlAttributes)
<span class="fa fa-key form-control-feedback left" aria-hidden="true"></span>
</div>
<div class="item col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control has-feedback-left", placeholder = "E-mail", required = "required" })
<span class="fa fa-envelope form-control-feedback left" aria-hidden="true"></span>
</div>
<div class="item col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
#Html.TextBoxFor(m => m.PhoneNumber, new { #class = "form-control has-feedback-left", placeholder = "Teléfono" })
<span class="fa fa-phone form-control-feedback left" aria-hidden="true"></span>
</div>
<div class="item col-md-12 col-sm-12 col-xs-12 form-group">
#Html.DropDownListFor(m => m.City, new SelectList(new List<SelectListItem>()), new { style = "width: 100%" })
</div>
<div class="item col-md-12 col-sm-12 col-xs-12 form-group">
#Html.DropDownListFor(m => m.Role, new SelectList(new List<SelectListItem>()), new { style = "width: 100%" })
</div>
<div class="item col-md-12 col-sm-12 col-xs-12 form-group">
#Html.DropDownListFor(m => m.Empresas, new SelectList(new List<SelectListItem>()), new { style = "width: 100%", multiple = "multiple" })
</div>
<div class="item col-md-12 col-sm-12 col-xs-12 form-group">
Está Vigente
#Html.CheckBoxFor(m => m.Vigente, new { #class = "flat" })
</div>
}
Please change the type of City Property in UserViewModal
public string City { get; set; }
Then it will return selected option value to controller for e.g
<select
<option value="1">Delhi </option>
<option value="2">Surat </option>
</select>
if you select Delhi then it will assign value 1 to property
I wonder there's show nothing in your dropdown.
In your view model, it should contain at least two properties, such as AvailableCities and City.
public List<SelectListItem> AvailableCities { get;set; }
public string City { get;set; }
AvailableCities contains all cities which should show in dropdow. And the City is using for getting the value user selected.
In your view,
#Html.DropDownListFor(m => m.City, Model.AvailableCities, new { #class = "form-control" })
For now, you should see the dropdown shawn and which could get the selected value in your action.

MVC parent child kind of model form submit doesn't send child collection to controller

I have a company model and it has employees list model as shown below
public class Company
{
[Required]
[Display(Name = "Company Name")]
public string Name { get; set; }
public List<EmployeeModel> Managers { get; set; }
}
and the Employee model as below
public class EmployeeModel
{
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
}
and my parent view is as shown below
#using (Html.BeginForm("CompanySignupSuccess", "Home", FormMethod.Post, new { #class = "horizontal-form", role = "form", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary("", new { #class = "text-danger" })
<div>
<div class="form-group">
#Html.LabelFor(m => m.Name, new { #class = "control-label" })<span class="required">*</span>
#Html.TextBoxFor(m => m.Name, new { #class = "form-control" })
</div>
<div class="form-group">
<label for="file">Logo:</label>
<input type="file" name="logo" id="logo" accept=".png,.jpg,.jpeg" />
</div>
<div id="managerList">
<div id="editorRowsManagers">
#foreach (var item in Model.Managers)
{
#Html.Partial("DetailsView", item)
}
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-default pull-right" value="Send" />
</div>
</div>
}
and the partial view shown below
#model yourAssembly.EmployeeModel
<div style="border:1px solid;margin:20px; padding:10px;">
Manager Details:
<div class="form-group">
#Html.LabelFor(m => m.Name, new { #class = "control-label" })
#Html.TextBoxFor(m => m.Name, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.Email, new { #class = "control-label" }) <span class="required">*</span>
#Html.TextBoxFor(m => m.Email, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.Phone, new { #class = "control-label" }) <span class="required">*</span>
#Html.TextBoxFor(m => m.Phone, new { #class = "form-control phoneno" })
</div>
</div>
When I click on submit button, the model that goes to controller does have only Name and Logo properties filled in and the list object(Managers) is null, so I am not sure what is that I am missing here. BTW, I used the list of employees , because I would like add more employees by having a 'Add' button, and the Add button will just render another partial view.
public ActionResult CompanySignupSuccess(Company model)
{
if (ModelState.IsValid)
{
//do some process
}
else
{
ModelState.AddModelError("", "Invalid Data entered.");
}
// If we got this far, something failed, redisplay form
return View("CompanySignup", Model);
}
Can anyone please help me on how to send the child list object along with some properties on parent class when the Submit button is hit.
You cannot use a partial to generate controls for a collection unless you pass the HtmlFieldPrefix (refer this answer for an example). However the correct way to do this is to use an EditorTemplate. Rename your partial to EmployeeModel.cshtml (i.e. to match the name of the class) and move it to the /Views/Shared/EditorTemplates folder (or /Views/YourControllerName/EditorTemplates folder).
Then replace your loop in the view with
#Html.EditorFor(m => m.Managers)
which will correctly generate the necessary name attributes for binding, i.e
<input ... name="Managers[0].Name" />
<input ... name="Managers[1].Name" />
etc (currently all your generating is duplicate name attributes (and duplicate id attributes which is invalid html)

Bootstrap glyphicon with MVC

Withour Razor syntax I can use glyphicon like that:
<div id="addIndirectCityBtn" class="btn btn-success btn-xs">
<span class="glyphicon glyphicon-plus"></span> Add
</div>
And it works perfect, glyphicon with textbox using razor syntax as below
#Html.TextBoxFor(model => model.From.City, new { #id = "cityFrom", #class = "form-control", #placeholder = "City", #style = "margin-bottom: 10px;" })
Where should I use glyphicon to have it in textbox or next to textbox
You can use input group in bootstrap, form-control class will put the object 100% width of box, so you need to group them.
Here is an example
<div class="input-group">
#Html.TextBoxFor(model => model.From.City, new { #id = "cityFrom", #class = "form-control", #placeholder = "City", #style = "margin-bottom: 10px;" }
<span class="input-group-addon"><i class="glyphicon glyphicon-plus"></i> Add</span>
</div>
How To use Glyphicons in Mvc Using Model
for example :
Model
public class Menu
{
public int Id { get; set; }
public string Name { get; set; }
public string Menuicon { get; set; }
}
Controller
[HttpPost]
public ActionResult Index(Menu m)
{
ViewBag.Message = m.Menuicon;
return View(m);
}
Index View
#model projectname.Models.Menu
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.LabelFor(Model => Model.Name)<br />
#Html.EditorFor(Model => Model.Name)<br />
#Html.LabelFor(Model => Model.Menuicon)<br />
#Html.EditorFor(Model => Model.Menuicon)<br />
<input type="submit" value="Save">
}
<br />
<div>
<span class="#ViewBag.Message"></span>
</div>
Result

modelstate.isvalid not getting all the errors

I have this model :
[Required(ErrorMessage = "Please provide a valid EmailAddress")]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required(ErrorMessage = "Please provide a company name")]
[Display(Name = "Company")]
public string CompanyName { get; set; }
[Required(ErrorMessage = "Please provide a username")]
[Display(Name = "Username")]
public string UserName { get; set; }
[Required(ErrorMessage = "Please select at least one language")]
public int[] SelectedLanguages { get; set; }
[Required(ErrorMessage = "Please select at least one business unit")]
public int[] SelectedBusinessUnits { get; set; }
Now when I do a post from my form using this model and I don't provide any of the values, I only get errormessages for Email, Company and UserName.
I don't get messages for the SelectedLanguages or the SelectedBusinessUnits.
What am i doing wrong?
THis is the view
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Create a new account.</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.CompanyName, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.CompanyName, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.UserName, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Email, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#foreach (var la in Model.Languages)
{
<input type="checkbox"
name="SelectedLanguages" value="#la.Id" id="#la.Id" />
<label for="#la">#la.Title</label>
}
</div>
<div class="form-group">
#foreach (var bu in Model.BusinessUnits)
{
<input type="checkbox"
name="SelectedBusinessUnits" value="#bu.Id" id="#bu.Id" />
<label for="#bu.Id">#bu.Title</label>
}
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Register" />
</div>
</div>
}
I think you have to go the way of writing a custom validation routine accompanied with a ValidationAttribute. Don't think a simple "out-of-the-box" validator exists for checking if one or more values are present in an array.
Check out this SO post to point you in the right direction.
Basic setup:
public class ArrayContainsValueAttribute: ValidationAttribute
{
// your checks here (pseudo)
if(!array.Any())
return false;
return true;
}
[ArrayContainsValue(ErrorMessage = "Please select at least one business unit")]
public int[] SelectedBusinessUnits { get; set; }

Resources