My ASP.NET MVC 5 application's razor view uses two checkboxes:
<div class="form-group">
#Html.LabelFor(model => model.BoolField1, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.BoolField1, new { htmlAttributes = new { #class = "form-control", #id = "bool1" } })
#Html.ValidationMessageFor(model => model.BoolField1, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BoolField2, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.BoolField2, new { htmlAttributes = new { #class = "form-control", #id = "bool2" } })
#Html.ValidationMessageFor(model => model.BoolField2, "", new { #class = "text-danger" })
</div>
</div>
</div>
I'm trying implement the rule that BoolField2 cannot be true unless BoolField1 is also true. My jquery code:
function applyRule() {
var bool1Status = document.getElementById('bool1').checked;
var bool2Status = document.getElementById('bool2').checked;
if (bool2Status == true && bool1Status == false) {
// This is the sole error.
// Generate a suitable error message and display (how?)
}
}
The custom error generated at this code must be displayed into Html.ValidationMessageFor. How can I achieve this?
First you need to correct syntax for EditorFor () it should be like following
#Html.EditorFor(model => model.BoolField1, new { #class = "form-control", #id = "bool1" })
instead of
#Html.EditorFor(model => model.BoolField1, new { htmlAttributes = new { #class = "form-control", #id = "bool1" } })
Now after having this correction you may write custom jQuery logic to achieve same. Here is the code.
$(function () {
$('#bool2').on('click', function (e) {
//Get the state of 1st checkbox
var isFirstCheck = $('#bool1').is(":checked");
if (isFirstCheck==false) {
//dispay message if you need. Below line of code will prevent user to select 2nd checkbox
e.preventDefault();
}
})
});
Related
My editorfor onChangeEvent isn't working and I can't figure out why.
here is my javascript function
<script type="text/javascript">
function OnChangeEvent() {
alert("value is changed");
var compQty = $('#compQTY').val();
//do other functions here also like change button
//if decrease add below
if (compQty < #Model.comp_qty) {
btn.Attributes.Add("onclick", "clicked(event)");
}
}
<script>
and here is my editorFor
<div class="form-group">
#Html.LabelFor(model => model.comp_qty, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#if (ViewBag.isValid == false)
{
#Html.TextBoxFor(model => model.comp_qty, new { disabled = "disabled", #Value = Model.comp_qty, #readonly = "readonly" })
}
else
{
#Html.EditorFor(model => model.comp_qty, new { htmlAttributes = new { onchange = "OnChangeEvent(this)", min = 0, #class = "form-control", #id = "compQTY" } })
#Html.ValidationMessageFor(model => model.comp_qty, "", new { #class = "text-danger" })
}
</div>
</div>
from what I have googled this should work but it is not. Can anybody help me figure out what I'm missing or what the possible solution is?
This question already has an answer here:
Submit same Partial View called multiple times data to controller?
(1 answer)
Closed 5 years ago.
I have a drop-down list (where multiple options can be selected) and two input boxes inside another div with id 'showInvestmentForm'.Upon selection of drop-down items,I want to produce those text boxes with respect to the number of drop-down items selected.
I want these text boxes to have different Names but I cant find a way to provide them different Names in such a way that their input values get passed to the controller.
This is a part of my Controller:-
foreach(var data in propertyViewModel.PropertyInvestors)
{
FounderInvestment founderInvestment = new FounderInvestment
{
Id = propertyViewModel.FounderInvestmentViewModel.Id ?? 0,
InstallmentPeriod = propertyViewModel.FounderInvestmentViewModel.InstallmentPeriod,
InvestorId = Convert.ToInt32(data),
PropertyId = property.Id,
Investment = propertyViewModel.FounderInvestmentViewModel.Investment
};
_founderInvestmentQueryProcessor.Create(founderInvestment);
}
This is my dropdown:-
<div class="form-group">
#Html.LabelFor(model => model.PropertyInvestors, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.PropertyInvestors, (IEnumerable<SelectListItem>)#ViewBag.Investors, "Select", htmlAttributes: new {#id="dropdown", #class = "form-control",#multiple="multiple" })
#Html.ValidationMessageFor(model => model.PropertyInvestors, "", new { #class = "text-danger" })
</div>
</div>
These are the textboxes:-
<div id="showInvestmentForm" style="display:none">
<div class="form-group">
#Html.LabelFor(model => model.FounderInvestmentViewModel.Investment, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FounderInvestmentViewModel.Investment, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FounderInvestmentViewModel.Investment, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FounderInvestmentViewModel.InstallmentPeriod, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FounderInvestmentViewModel.InstallmentPeriod, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FounderInvestmentViewModel.Investment, "", new { #class = "text-danger" })
</div>
</div>
</div>
If I understood correctly your problem is that input texts are not posted to your Controller.
Would be usefult if you write the Controller's code to check the full scenario.
Anyway a common mistake, that could be your case, when using Mvc helpers is that when you point to a nested property, the generated name of the input is not the final property name but a path to that property.
#Html.EditorFor(model => model.FounderInvestmentViewModel.InstallmentPeriod, ..)
In your case that code produce an input with name FounderInvestmentViewModel_InstallmentPeriod, and not just InstallmentPeriod.
If in your controller you expect a parameter named "InstallmentPeriod" that would not be received, because the page posts a parameter named "FounderInvestmentViewModel_InstallmentPeriod"
My cascading drop down box work fine from within visual studio 2015 and iisexpress. But when hosting on IIS or selecting IIS as server in visual studio the controller action to populate the second drop drown box is not called!
I'm new to Javascript and and not very firm with asp.net mcv with I use here.
I use VS2015, ASP.NET Mvc
Create.cshtml:
#model Bethesda2017.Models.AuftragEditViewModel
#{
ViewBag.Title = "Neuer Reparaturauftrag";
}
<style>
body {
background: url(/Bilder/Bethesda4Web.jpg);
background-position: right top;
background-size: 12%;
background-repeat: no-repeat;
}
</style>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal body">
<h4>Neuer Reparaturauftrag</h4>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
-- Some irrelavant controls extracted here ----
<div class="form-group">
#Html.LabelFor(model => model.STORT_ID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.DropDownListFor( model => model.STORT_ID, Model.StandortListe, "Bitte wählen!", new { htmlAttributes = new { #class = "form-control" } })*#
#Html.DropDownListFor(model => model.STORT_ID, Model.StandortListe, "Bitte wählen!", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.STORT_ID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TRAKT_ID, htmlAttributes: new { #class = "control-label col-md-2" })
#*#Html.DropDownListFor(model => model.TRAKT_ID, Model.TraktListe, "", new { #class = "form-control col-md-2" } )*#
<div class="col-md-10">
#Html.DropDownListFor(model => model.TRAKT_ID, Model.TraktListe, "", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TRAKT_ID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ETAGE_ID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ETAGE_ID, Model.EtageListe, "", new { #class = "form-control" } )
#Html.ValidationMessageFor(model => model.ETAGE_ID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.RAUM_ID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.RAUM_ID, Model.RaumListe, "", new { #class = "form-control" } )
#Html.ValidationMessageFor(model => model.RAUM_ID, "", new { #class = "text-danger" })
</div>
</div>
#*<div class="form-group">
#Html.LabelFor(model => model.DerAuftrag.FHD_KOMPLETT, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DerAuftrag.FHD_KOMPLETT, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DerAuftrag.FHD_KOMPLETT, "", new { #class = "text-danger" })
</div>
</div>*#
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Speichern" class="btn btn-default" />
</div>
</div>
</div>
}
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
var trakt_idUrl = '#Url.Action("FetchTrakte", "Auftrag")';
var trakte = $('#TRAKT_ID');
var etage_idUrl = '#Url.Action("FetchEtagen", "Auftrag")';
var etagen = $('#ETAGE_ID');
var raume = $('#RAUM_ID');
var raum_idUrl = '#Url.Action("FetchRaume", "Auftrag")';
$('#STORT_ID').change(function () {
trakte.empty();
etagen.empty();
raume.empty();
$.getJSON(trakt_idUrl, { STORT: $(this).val() }, function (data) {
if (!data)
{ return; }
trakte.append($('<option></option>').val('').text('Bitte Trakt wählen!'));
$.each(data, function (index, item) {
trakte.append($('<option></option>').val(item.TRAKT_ID).text(item.BEZEICHNUNG));
})
}
)
}
)
$('#TRAKT_ID').change(function () {
etagen.empty();
raume.empty();
$.getJSON(etage_idUrl, { STORT: $(this).val() }, function (data) {
if (!data)
{ return; }
etagen.append($('<option></option>').val('').text('Bitte Etage wählen!'));
$.each(data, function (index, item) {
etagen.append($('<option></option>').val(item.ETAGE_ID).text(item.BEZEICHNUNG));
})
}
)
}
)
$('#ETAGE_ID').change(function () {
raume.empty();
$.getJSON(raum_idUrl, { STORT: $(this).val() }, function (data) {
if (!data)
{ return; }
raume.append($('<option></option>').val('').text('Bitte Raum wählen!'));
$.each(data, function (index, item) {
raume.append($('<option></option>').val(item.RAUM_ID).text(item.BEZEICHNUNG));
})
}
)
}
)
</script>
When selecting an entry in the first drop down box the java script
$('#STORT_ID').change(function () ...
gets called and trakte, etagen and raume are set empty but the next step:
$.getJSON(trakt_idUrl, { STORT: $(this).val() }, function (data) {...
which should call the method
public JsonResult FetchTrakte(string STORT )
{
List<Trakt> _l = FetchTrakteList(STORT);
if ( _l.Count<1 )
{
Trakt _s0 = new Trakt() { TRAKT_ID = "00", BEZEICHNUNG = "keine Daten" };
_l.Add(_s0);
}
return Json(_l, JsonRequestBehavior.AllowGet);
}
is only called when using iisexpress but not with IIS!
Where is the problem or how to examine what is going on here?
I would like my Checkbox to disable EditorsFor if it is unchecked and enable them if it is checked. I know I have to use JavaScript, I found some codes in net, but it seems that they don't work.
Here is my View code:
#{Html.RenderPartial("_PartialError");}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
(...)
<div class="form-group">
#Html.LabelFor(model => model.Czy_zuzywalny, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Czy_zuzywalny)
#Html.ValidationMessageFor(model => model.Czy_zuzywalny, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Ilosc_minimalna, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Ilosc_minimalna, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Ilosc_minimalna, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Ilosc_optymalna, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Ilosc_optymalna, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Ilosc_optymalna, "", new { #class = "text-danger" })
</div>
</div>
(...)
}
And I wrote something like this and put in js file (ofc at the end of this code is ), but it doesn't work...
$(document).ready(function ()
{
$("#Czy_zuzywalny").click(function ()
{
if ($("#Ilosc_minimalna").attr("disabled") == "")
{
$("#Ilosc_minimalna").attr("disabled", "disabled");
$("#Ilosc_optymalna").attr("disabled", "disabled");
$("#Ilosc_minimalna").attr("value", "0");
$("#Ilosc_optymalna").attr("value", "0");
}
else
{
$("#Ilosc_minimalna").attr("disabled", "");
$("#Ilosc_optymalna").attr("disabled", "");
}
});
});
Nothing happens even if I check or uncheck my checkbox. Can anyone help me with that?
Change your jQuery code to:
$(document).ready(function () {
$("#Czy_zuzywalny").click(function () {
if ($("#Ilosc_minimalna").is('[disabled=disabled]')) {
$("#Ilosc_minimalna").removeAttr("disabled");
$("#Ilosc_optymalna").removeAttr("disabled");
}
else {
$("#Ilosc_minimalna").attr("disabled", "disabled");
$("#Ilosc_optymalna").attr("disabled", "disabled");
$("#Ilosc_minimalna").attr("value", "0");
$("#Ilosc_optymalna").attr("value", "0");
}
});
});
The if condition on your code never actually evaluates to true because in an enabled input, the 'disabled' attribute doesn't have a value of an empty string. it just doesn't exist (thus the use of removeAttr("disabled")).
UPDATE: Working JSFiddle here
UPDATE 2:
In order to add the script in the Create view and have it show after the jQuery script tag in the rendered HTML do this:
First add a call to RenderSection in your Layout file just before the closing </body> tag like this:
#RenderSection("scripts", required: false)
This will give you the ability to include a 'scripts' section in your views, the contents of which, will appear instead of the RenderSection call in the final HTML. Note that the required: false parameter specifies that you don't have to include this section in every view.
Then in your Create view, outside of any section add this:
#section scripts {
<script src="/scripts/CheckBoxItemCreate.js"></script>
}
Hope this helps!
Here is my View:
#using (Html.BeginForm("SaveNewCustomer", "Dealer", FormMethod.Post, new { id = "myForm" }))
{
<div class="form-horizontal">
<div class="row">
<div class="form-group-1">
#Html.LabelFor(model => model.device.MotorType, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.MotorType, new { htmlAttributes = new { #class = "form-control required", placeholder = "Motor Type", required = "required" } })
</div>
<div class="form-group-1">
#Html.LabelFor(model => model.device.PowerRating, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.PowerRating, new { htmlAttributes = new { #class = "form-control required", placeholder = "Power Rating", required = "required" } })
</div>
<div class="form-group-1">
#Html.LabelFor(model => model.device.InstallationDate, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.InstallationDate, new { htmlAttributes = new { #class = "form-control datepicker required", placeholder = "Installation Date(MM/dd/yyyy)", required = "required" } })
</div>
<div class="form-group-1">
#Html.LabelFor(model => model.device.ActivationDate, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.ActivationDate, new { htmlAttributes = new { #class = "form-control datepicker required", placeholder = "Activation Date(MM/dd/yyyy)", required = "required" } })
</div>
<div class="form-group-1">
#Html.LabelFor(model => model.device.DataReceiveInterval, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.DataReceiveInterval, new { htmlAttributes = new { #class = "form-control required", placeholder = "Data receive Interval", required = "required" } })
</div>
<div class="form-group-1">
#Html.LabelFor(model => model.device.HasAMC, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.HasAMC, new { htmlAttributes = new { #class = "form-control required", #onchange = "OnChange();" } })
</div>
<div class="form-group-1" id="HasDate">
#Html.LabelFor(model => model.device.AMCExpiredDate, htmlAttributes: new { #class = "control-label col-lg-4" })
#Html.EditorFor(model => model.device.AMCExpiredDate, new { htmlAttributes = new { #class = "form-control required", placeholder = "AMCExpireDate(MM/dd/yyyy)", required = "required", title = "Enter AMC Expire Date" } })
</div>
<button style="margin-left:33%;" id="action" class="btn btn-sm btn-primary col-lg-2 " type="button" name="action" value="SaveDeviceInfo"><strong>Save</strong></button>
</div>
</div>
}
My javascript script is
<script type="text/javascript">
$(document).ready(function () {
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myForm" ).validate({
rules: {
"client.ContactNo": {
required: true
}
}
});
$("#action").click(function () {
if (!$("#myForm").validate()) { // Not Valid
return false;
} else {
Save();
}
});
function Save() {
var frm = $("#myForm").serialize();
$.ajax({
url: "/Dealer/SaveNewCustomer",
data: frm,
type: "POST",
success: function (result) {
if (result == "true") {
//alert(result);
window.location.href = "/Dealer/Customers?Success=true&Message=Customer updated successfully.";
}
else
toastr.error(result);
}
});
}
</script>
Problem is Validation not fire. In If else condition it is showing false and direct store the value in database. Could you please help me?
Is anything wrong in my code? Give me suggestions please.
Thanks in advance.
.validate() is only the initialization method.
.valid() is the method used for testing the form.
if (!$("#myForm").valid()) { ....
It's a moot point because your .ajax() function belongs inside the submitHandler option of the plugin anyway. The submitHandler callback only fires when the form is valid, thereby you can entirely eliminate your whole if/then click handler function (however you must change the button element into a type="submit").
$(document).ready(function () {
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myForm" ).validate({
rules: {
"client.ContactNo": {
required: true
}
},
submitHandler: function(form) { // only fires when form is valid
var frm = $(form).serialize();
$.ajax({
url: "/Dealer/SaveNewCustomer",
data: frm,
type: "POST",
success: function (result) {
if (result == "true") {
//alert(result);
window.location.href = "/Dealer/Customers?Success=true&Message=Customer updated successfully.";
}
else
toastr.error(result);
}
});
return false;
}
});
});
NOTE: If you happen to be using the unobtrusive-validation plugin as included within your ASP framework, then the .validate() method is constructed and called automatically. If that's the case, then your call to .validate() will be ignored, and you would put any plugin options only within jQuery.validator.setDefaults().
You are missing your form tags from your html. Also, you dont have anything with the id of myform. So your trying to validate #myform in your jquery but there is no myform. You would need to add your form tags and give it an id of myform.