MVC 5, Using Checkbox for same model property twice in a page but inside different forms - asp.net-mvc

Model property which I intend to use inside two forms
public class TestModel
{
[Display(Name = "Terms Accepted")]
[Range(typeof(bool), "true", "true", ErrorMessage = "You need to accept terms and conditions to proceed!")]
public bool TermsAccepted { get; set; }
}
view Page
<form id="form1">
<div class="row">
<div class="col-md-3">
#Html.CheckBoxFor(m => m.TermsAccepted) I accept terms and conditions
#Html.ValidationMessageFor(m => m.TermsAccepted, new { #id = "chk1" })
</div>
<div class="col-md-3">
<input type="submit" id="button1" onclick="return isFormValid('form1');" value="Submit Form 1"/>
</div>
</div>
</form>
<form id="form2">
<div class="row">
<div class="col-md-3">
#Html.CheckBoxFor(m => m.TermsAccepted, new { #id = "chk2" }) I accept terms and conditions
#Html.ValidationMessageFor(m => m.TermsAccepted)
</div>
<div class="col-md-3">
<input type="submit" id="button2" onclick="return isFormValid('form2');" value="Submit Form 2"/>
</div>
</div>
</form>
When this UI is rendered on the page, checkbox inside the 1st form do contains attributes for RangeDataAnnotation while checkbox inside 2nd form doesn't have any attributes for data annotation. So this results into 2nd form doesn't throw any validation on submission.
Html of checkboxes which get rendered on UI
Inside form 1:
<input name="TermsAccepted" class="input-validation-error" id="chk1" aria-describedby="TermsAccepted-error" type="checkbox" value="true" data-val="true" data-val-range-min="True" data-val-range-max="True" data-val-range="You need to accept terms and conditions to proceed!">
Inside form 2:
<input name="TermsAccepted" id="chk2" type="checkbox" value="true">
Any suggestions to make this work in both forms?

Related

ASP.NET Core MVC validate not required fields

My page is validating a field that is not required when I submit, even though there is no validation configured for this field.
Create.cshtml
#model Lawtech.App.ViewModels.ProcessoViewModel
#{
ViewData["Title"] = "Novo processo";
}
<h3 style="padding-top: 10px">#ViewData["Title"] </h3>
<hr />
<div class="row">
<div class="col-md-12">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="row">
<div class="form-group col-md-4">
<label asp-for="Numero" class="control-label"></label>
<input asp-for="Numero" class="form-control" />
<span asp-validation-for="Numero" class="text-danger"></span>
</div>
<div class="form-group col-sm-4">
<label asp-for="IdArea" class="control-label"></label>
<div class="input-group">
<select id="slcArea" asp-for="IdArea" class="form-control select2"></select>
<div class="input-group-btn">
<a asp-action="CreateArea" class="btn btn-info" style="border-radius:0 0.25rem 0.25rem 0" data-modal="">
<span class="fa fa-plus"></span>
</a>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-6 mt-4">
<input type="submit" value="Cadastrar" class="btn btn-sm btn-primary" />
<a class="btn btn-sm btn-info" asp-action="Index">Voltar</a>
</div>
</div>
</form>
</div>
</div>
<div id="myModal" class="modal fade in">
<div class="modal-dialog">
<div class="modal-content">
<div id="myModalContent"></div>
</div>
</div>
</div>
ViewModel
public class ProcessoViewModel
{
[Key]
public int Id { get; set; }
[DisplayName("Número")]
[Required(ErrorMessage = "O campo número é obrigatório")]
public string Numero { get; set; }
[DisplayName("Área")]
public int IdArea { get; set; }
}
Controller
In Controller Create method, nothing happens, because all validation takes place on the client side.
[Route("novo-processo")]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(ProcessoViewModel processoViewModel)
{
try
{
if (!ModelState.IsValid) return View(processoViewModel);
await _processoBLL.Insert(_mapper.Map<ProcessoDTO>(processoViewModel));
if (!ValidOperation()) return View(processoViewModel);
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
Inspecting in Chrome I see this generated html for the field that I didn't require validation, I don't know if it could be something related to Jquery.Unobtrusive but I can't remove it either because other fields will be validated.
<select id="slcArea" class="form-control select2 select2-hidden-accessible input-validation-error" data-val="true" data-val-required="The Área field is required." name="IdArea" data-select2-id="slcArea" tabindex="-1" aria-hidden="true" aria-describedby="slcArea-error" aria-invalid="true"></select>
Why is this validation taking place that I have not defined the field as required?
Not nullable properties (that is properties with value types) are always required. Use nullable types (reference types) for properties if they should not be required - eg. int?.
You can always use formnovalidate on any input you don't want validated.
<input asp-for="Numero" formnovalidate="formnovalidate" class="form-control" />
This way there is no need to change your model. This is demonstrated at W3Schools

Gridmvc filtering without query in url

I'm using GridMvc and I'm filtering data. I'd like to hide filter query in the url like http://www.mypage.com/Overview?Name=yyy
My form is defined as:
<form class="form-inline" method="POST" action="#Url.Action("Filter", Request.QueryString)">
<div class="form-group>
#Html.LabelFor(c => c.Name)
#Html.TextBoxFor(c => c.Name, new { placeholder = "Filter", #class = "form-control" })
<button type="submit" class="btn btn-default"><i class="glyphicon glyphicon-search"></i> Search</button>
</div>
</form>
And the action
[HttpPost]
public ActionResult Filter(FilterModel model)
But I always see the query. It's possible to hide query string?
You cound hide your query if you put all you data in hidden fields instead of Request.QueryString.
I mean if your Request.QueryString looks like param1=test1&param2=test2 you should render you view like this:
<form class="form-inline" method="POST" action="#Url.Action("Filter")">
<input type="hidden" name="param1" value="test1" />
<input type="hidden" name="param2" value="test2" />
<div class="form-group>
#Html.LabelFor(c => c.Name)
#Html.TextBoxFor(c => c.Name, new { placeholder = "Filter", #class = "form-control" })
<button type="submit" class="btn btn-default"><i class="glyphicon glyphicon-search"></i> Search</button>
</div>
</form>
MVC binding will bind all hidden values on POST according to name property of this hidden inputs.
You should just fill inputs value (replace test1 and test2 with your values from Request.QueryString)

ASP.NET MVC - Multiple Radio Buttons selections being allowed, why?

Question Background:
I have two groups of Radio buttons in a menu. One group features 2 Radio buttons that allow a user to select a group of items to being sorted and displayed by their price either from 'High To Low' or 'Low To High'.
The second group of Radio buttons allows users to search for results from 3 different online marketplaces.
The Issue:
Currently the first group of Radio buttons (the price sort group) is working fine, if I click 'High To Low' then that Radio buttons will be selected, if I then select 'Low To High' this will be selected.
The second group with the 3 radio buttons for the marketplaces is causing me issues. This is allowing all three radio buttons to be checked instead of just one, and once all checked the user cannot unchecked them, as shown:
The Code:
this is the MarkUp in my View. I am using RadioButtonsFor Razer controls binding each Radio button to a specific property from the ViewModel.
<div class="form-group">
<div class="maxPricePad">
<label>#Html.RadioButtonFor(model => model.amazonAndEbay, true, new { id = "amazonEbayBox", #checked = "true" })<img class="originPic" src="#Url.Content("~/Images/amazon.png")" /> <img class="originPic" src="#Url.Content("~/Images/ebay.png")" /> Amazon & Ebay</label>
</div>
</div>
<div class="form-group">
<div class="maxPricePad">
<label>#Html.RadioButtonFor(model => model.amazonOnly, true, new { id = "amazonCheckBox" })<img class="originPic" src="#Url.Content("~/Images/amazon.png")" /> Amazon Only</label>
</div>
</div>
<div class="form-group">
<div class="maxPricePad">
<label>#Html.RadioButtonFor(model => model.ebayOnly, true, new { id = "ebayCheckBox" })<img class="originPic" src="#Url.Content("~/Images/ebay.png")" /> Ebay Only</label>
</div>
</div>
The HomePageVM:
public class HomePageVM
{
public bool highToLow { set; get; }
public bool lowToHigh { set; get; }
public bool amazonAndEbay { set; get; }
public bool amazonOnly { set; get; }
public bool ebayOnly { set; get; }
}
The Radio Buttons as rendered in Chrome:
<div class="form-group">
<div class=" maxPricePad">
<label>
<input checked="true" data-val="true" data-val-required="The amazonAndEbay field is required." id="amazonEbayBox" name="amazonAndEbay" type="radio" value="True"><img class="originPic" src="/Images/amazon.png"> <img class="originPic" src="/Images/ebay.png"> Amazon & Ebay</label>
</div>
</div>
<div class="form-group">
<div class=" maxPricePad">
<label>
<input data-val="true" data-val-required="The amazonOnly field is required." id="amazonCheckBox" name="amazonOnly" type="radio" value="True"><img class="originPic" src="/Images/amazon.png"> Amazon Only</label>
</div>
</div>
<div class="form-group">
<div class=" maxPricePad">
<label>
<input data-val="true" data-val-required="The ebayOnly field is required." id="ebayCheckBox" name="ebayOnly" type="radio" value="True"><img class="originPic" src="/Images/ebay.png"> Ebay Only</label>
</div>
</div>
Any help determing why I am getting all 3 checkboxes to select would be much appreciated.
Very sill lapse in concentration and just realized I'm using different models values for each property instead of one common one.
If you want only one selection from the group of radio buttons then you have to give them a common name, which will group them together and allow you to select only one from the group. The example lets you choose either Camaro or Mustang, but not both of them, since they have the same name, which means that they belong to the same group of items:
<input type="radio" name="car"/> Camaro <br/>
<input type="radio" name="car"/> Mustang <br/>
This example will let you choose one car (Camaro or Mustang) and one color (Yellow or Green):
<input type="radio" name="car"/> Camaro <br/>
<input type="radio" name="car"/> Mustang <br/>
<input type="radio" name="color"/> Yellow<br/>
<input type="radio" name="color"/> Green<br/>
The reason you are getting all three checkboxes selected in the Marketplaces group is that you're using separate names for each radio button in this button group. All buttons that ought to be mutually exclusive should be part of one group represented by one label. Also, since you're declaring each radio button separately and individually, I think there's no need to use HtmlRadioButtonFor. Simply try the following changes to your code. Note that I named your radio button group as, "Marketplaces":
The Code:
<div class="form-group">
<div class="maxPricePad">
<label>#Html.RadioButton("Marketplaces", model.amazonAndEbay, new { id = "amazonEbayBox", #checked = "true" })<img class="originPic" src="#Url.Content("~/Images/amazon.png")" /> <img class="originPic" src="#Url.Content("~/Images/ebay.png")" /> Amazon & Ebay</label>
</div>
</div>
<div class="form-group">
<div class="maxPricePad">
<label>#Html.RadioButton("Marketplaces", model.amazonOnly, new { id = "amazonCheckBox" })<img class="originPic" src="#Url.Content("~/Images/amazon.png")" /> Amazon Only</label>
</div>
</div>
<div class="form-group">
<div class="maxPricePad">
<label>#Html.RadioButton("Marketplaces", model.ebayOnly, new { id = "ebayCheckBox" })<img class="originPic" src="#Url.Content("~/Images/ebay.png")" /> Ebay Only</label>
</div>
</div>

Unobtrusive JQuery Validation not working in popup PartialViews [duplicate]

This question already has an answer here:
Required field validations not working in JQuery Popup MVC 4
(1 answer)
Closed 7 years ago.
I have the following a partial view in asp.net 5 mvc 6 project. The partial view is shown as a jquery ui dialog and is loaded dynamically when the user clicks a button in the parent view page.The issue is that the Unobtrusive JQuery Validation does not work after I enter invalid entires and clicked submit.
I have done all the procedures needed to make Unobtrusive JQuery Validation work and it works in Non partial views.
Here is my code
my partial view name EquipmentEditTemplate.cshtml
#model MyProject.Models.EquipmentViewModel
#*<form role="form" name="FormPost" asp-controller="Asset" method="post" asp-action="SaveEq" data-ajax="true" id="FrmGrid_grdLocation1" class="FormGrid form-horizontal" style="width:477px;height:703px;">*#
#*<form asp-controller="Asset" asp-action="SaveEq" method="post" style="width:600px;height:703px;" class="form-horizontal" >*#
<div class="FormError bg-danger" style="display:none;"></div><div class="tinfo topinfo"></div><div class="modal-body">
<div style="margin-left:15px;">
<div class="form-group">
<label asp-for="EquipmentID" class="col-sm-2 control-label">Equipment ID:</label>
<div class="col-sm-10">
<input asp-for="EquipmentID" class="FormElement form-control" />
<span asp-validation-for="EquipmentID" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Email" class="col-sm-2 control-label">Email:</label>
<div class="col-sm-10">
<input asp-for="Email" class="FormElement form-control" />
</div>
</div>
<div class="form-group">
<label asp-for="Department" class="col-sm-2 control-label">Department:</label>
<div class="col-sm-10">
<input type="text" id="Department" name="Department" value="#Model.Department" role="textbox" class="FormElement form-control">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Sign in</button>
</div>
</div>
</div>
</form>
I have the code below in the main view as shown I have included the validation scripts in there equipment.cshtml
#{
ViewData["Title"] = "Equipment";
}
<h2>#ViewData["Title"].</h2>
<h3>#ViewData["Message"]</h3>
#section scripts{
#{await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
<script src="~/js/equipment.js" type="text/javascript"></script>
}
I have my model class defined as follows
public class EquipmentViewModel
{
[Required]
public int EquipmentID { get; set; }
[EmailAddress]
public string Email{ get; set; }
public int Description{ get; set; }
}
}
When you've loaded a form in to your DOM dynamically then add the below line at the end of your partial view.
$(document).ready(function() {
$.validator.unobtrusive.parse($('#yourform'));
});

how to use radiobuttonlist in mvc4

I need to create a simple radio button list selection to choose from the following values:
Agree
Disagree
Not sure
How would we add it in the following razor view? Is it better to create an enum of these values in the QuestionModel and use foreach to bind with html helper.
Any example or ideas?
#model Survey.Models.Question
#using (Html.BeginForm("Index", "Home", new { QuestionId = Model.QuestionId }))
{
<h2>Survey</h2>
<fieldset>
<legend>Please Choose</legend>
<p>
Question ID:
#Model.QuestionId
</p>
<p>
Description:
#Model.Description
</p>
<input type="submit" value="Next" id="submitButton" />
</fieldset>
}
Using the ASP.NET Html Helpers, there are three various methods you can use for each of the different helpers supplied for radio buttons.
Method 1
A simple way to make a radio button list:
<div>
<label>
#Html.RadioButton("Answer", "Agree")
Agree
</label>
</div>
<div>
<label>
#Html.RadioButton("Answer", "Disagree")
Disagree
</label>
</div>
<div>
<label>
#Html.RadioButton("Answer", "Not Sure")
Not Sure
</label>
</div>
Method 2
The above code will post the checked value with a name of "Answer" to the server when you click Submit. If you would like to make this strongly typed, as you did with Model.QuestionId and Model.Description, you could add a Answer property to your model and do the following:
<div>
<label>
#Html.RadioButtonFor(m => m.Answer, "Agree")
Agree
</label>
</div>
<div>
<label>
#Html.RadioButtonFor(m => m.Answer, "Disagree")
Disagree
</label>
</div>
<div>
<label>
#Html.RadioButtonFor(m => m.Answer, "Not Sure")
Not Sure
</label>
</div>
Method 3
Finally, if you would like to get fancy, you can use an enum. Place the following in your controller:
public enum AnswerType {
Agree,
Disagree,
NotSure
}
Next, add the property to your model:
public AnswerType AnswerType { get; set; }
And then add the following to your view:
#Html.RadioButtonForEnum(m => m.AnswerType)
Hope this helps!
this will work
Radio button for model
#using (Html.BeginForm())
{
foreach (var department in Model.Departments)
{
#Html.RadioButtonFor(m => m.SelectedDepartment, department.Id) #department.Name
}
<input type="submit" value="Submit" />
}
In your viewmodel you could have a public int SelectedRating. You could make it a string and change the values from 114... to string values as well.
<div class="radio">
<label>
#Html.RadioButtonFor(x => x.SelectedRating, 114)
<span>Not Sure</span>
</label>
</div>
<div class="radio">
<label>
#Html.RadioButtonFor(x => x.SelectedRating, 115)
<span>Agree</span>
</label>
</div>
<div class="radio">
<label>
#Html.RadioButtonFor(x => x.SelectedRating, 116)
<span>Don't Agree</span>
</label>
</div>

Resources