MVC html helpers change hiddenfor attributes - asp.net-mvc

I have am using html helper fields below, my issue I need the make these hiddenfor elements not hidden when checkbox is checked.
#Html.HorizontalFormFieldFor(model => model.InsaatHizmetBedeli)
<div class="control-group">
#Html.LabelFor(model => model.tadilatMi, new { #class = "control-label" })
<div class="controls">
#if (!Model.tadilatMi.HasValue)
{
Model.tadilatMi = false;
}
#Html.CheckBoxFor(model => model.tadilatMi.Value, new { #Name="tadilatmi" });
</div>
</div>
#Html.HiddenFor(model => model.myHiddenProperty)
here is my jquery code:
$("input[name='tadilatmi']").on("change", function () {
if ($("input[name='tadilatmi']").is(":checked")) {
$("#myHiddenProperty").show()
}
})
of course it not works.. how can I achieve this ?

Your generating an input with type="hidden" which is always hidden. The jQuery.show() method is for toggling the display of elements styled with display:none; and its changes it to display:block;
You could do this by changing the type attribute
if ($("input[name='tadilatmi']").is(":checked")) {
$("#myHiddenProperty").attr('type', 'text')
}
or by making the input type="text" and styling it as hidden
#Html.TextBoxFor(model => model.myHiddenProperty)
with the following css
#myHiddenProperty {
display: none;
}
and then your original script will work.
I suspect however that you want to toggle the visibility back if the checkbox is then unchecked, in which case you should have an else block
if ($("input[name='tadilatmi']").is(":checked")) {
$("#myHiddenProperty").show()
} else {
$("#myHiddenProperty").hide()
}
Side note: your using an awful hack in order to make you checkbox bind to a nullable bool property (by chaninging the name attribute) and your label does not even work as a label (clicking on it will not toggle the checkbox). I recommend you use a view model with
public bool Tadilatmi { get; set; }
and in the view simply use
#Html.LabelFor(m => m.Tadilatmi , new { #class = "control-label" })
<div class="controls">
#Html.CheckBoxFor(m => m.Tadilatmi);
</div>
and change the script to (which is more efficient)
var hiddenElement = $('#myHiddenProperty');
$('#tadilatmi').change(function () {
if ($(this).is(":checked")) {
hiddenElement.show()
} else {
hiddenElement.hide()
}
})
Your myHiddenProperty property could then include a foolproof [RequiredIfTrue("Tadilatmi")] or similar conditional validation attribute.

Related

How to disable model view check box in .net mvc?

How to disable model view check box in .net mvc?
I tried with the syntax : new { disabled = "disabled" } but doesn't work.
<div class="col-sm-7 checkbox-inline text-left">
<label style="margin-right:15px"></label>
#Html.CheckBoxFor(model => model.Email, new { disabled = "disabled" } ) <label class="hthin" asp-for="Email" style="margin-right:30px"></label>
#Html.CheckBoxFor(model => model.Pager, new { disabled = "disabled" }) <label class="hthin" asp-for="Pager" style="margin-right:30px"></label>
#Html.CheckBoxFor(model => model.Landline, new { disabled = "disabled" }) <label class="hthin" asp-for="Landline" style="margin-right:30px"></label>
</div>
#Html.CheckBoxFor() - model object property should be boolean.
Thanks Stephen Muecke. I updated my answer. # symbol is used for reserved keywords. For example #class.
Thanks GregH. You catch it perfect.

radiobutton to display message

I have this model
public partial class PRB
{
public long PRB_ID { get; set; }
public string MEMBERSHIP_NUMBER { get; set; }
public Nullable<int> MEMBERSHIP_TYPE { get; set; }
public string REEGISTERED_BUSINESS_NAME { get; set; }
}
I want to make MEMBERSHIP_TYPE to be a radiobutton
<div class="form-group">
<div class="radio">
#Html.RadioButtonFor(m => m.MEMBERSHIP_TYPE, 1, new { id = "", #checked = "checked" }) Foreign Company
</div>
<div class="radio">
#Html.RadioButtonFor(m => m.MEMBERSHIP_TYPE, 2, new { id = "" }) Foreign Owned Nigerian Company
</div>
<div class="radio">
#Html.RadioButtonFor(m => m.MEMBERSHIP_TYPE, 3, new { id = "" }) Nigerian Company
</div>
</div>
If radiobutton MEMBERSHIP_TYPE that is clicked is 1, the message box displayed will be "You are a Grade A member". Then OK button will be clicked
If radiobutton MEMBERSHIP_TYPE that is clicked is 2, the message box displayed will be "You are a Grade B member". Then OK button will be clicked
If radiobutton MEMBERSHIP_TYPE that is clicked is 3, the message box displayed will be "You are a Grade C member". Then OK button will be clicked
Then, after the click of OK button for the message box, it will diplay what is shown below.
<div class="form-group">
#Html.LabelFor(model => model.REGISTERED_BUSINESS_NAME, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.REGISTERED_BUSINESS_NAME)
#Html.ValidationMessageFor(model => model.REGISTERED_BUSINESS_NAME)
</div>
</div>
Then the user will enter the Business name textbox.
Please help.
If your project includes jQuery, you can show message box when changing radio button selection using this simple code:
$('input[type=radio]').change(function () {
// radio button selection part
var value = parseInt($(this).val());
switch (value) {
case 1:
alert("You are a Grade A member");
break;
case 2:
alert("You are a Grade B member");
break;
case 3:
alert("You are a Grade C member");
break;
default:
// do something else
break;
}
// code to show/hide div or using modal popup here
});
Tips:
Use $(this).is(':checked') to check current value of radio button group(s).
If your radio button controls is more than given above, consider assign a class for corresponding radio buttons e.g. #Html.RadioButtonFor(m => m.MEMBERSHIP_TYPE, 1, new { id = "", #class = "classname" }) and set jQuery selector pointed to that CSS class such as $('.classname').change(function () { ... }).
Depending on what you need, EditorFor part can be presented as simple div wrapper or modal popup. If the former has used, give a value for id attribute to that div element and use hide()/show() method as toggle, like this example:
HTML
<div id="regname" class="form-group">
#Html.LabelFor(model => model.REGISTERED_BUSINESS_NAME, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.REGISTERED_BUSINESS_NAME)
#Html.ValidationMessageFor(model => model.REGISTERED_BUSINESS_NAME)
</div>
</div>
JS
$(document).ready(function () {
$('#regname').hide();
$('input[type=radio]').change(function () {
// see radio button selection code above
// show target div
$('#regname').show();
});
});
If the latter one is used, follow same procedure to give id attribute on div element (see also: "When creating a dialog with jquery, how do I hide the dialog div?"), then use dialog method like this example instead:
$(document).ready(function () {
$('#regname').dialog({
autoOpen: false,
modal: true
// other property settings here
});
$('input[type=radio]').change(function () {
// see radio button selection code above
// show target modal popup
$('#regname').dialog("open");
});
});
This is not a perfect explanation, but at least explain what should you do to show message box & displaying other part of view when changing radio button selection.

Html.ValidationMessageFor() not rendering <span> element

I've been using Html.ValidationMessageFor for quite a long time in MVC 3. All of a sudden this extension is no longer working for me, but only in a particular view. The extension is used in a <form> tag and the page has the jquery.validate.min.js and jquery.validate.unobtrusive.min.js attached (among others). I've checked other pages of the site, and those views use the same call and the <span> element is generated.
Here is the markup I'm using:
<form id="assistanceRequestDiv" class="form-group js-more-assistance js-hidden">
<p>#Translation.TextByDomain("Assistance", "need-further-assistance-contact-customer-support")</p>
<div class="content-block left-text-children">
<div class="content-block__quarter-column">
#Html.LabelFor(x => x.AssistanceRequestFirstName)
#Html.ValidationMessageFor(x => x.AssistanceRequestFirstName)
#Html.TextBoxFor(x => x.AssistanceRequestFirstName, new {#class = "form-control", required = "required"})
</div>
<div class="content-block__quarter-column">
#Html.LabelFor(x => x.AssistanceRequestLastName)
#Html.ValidationMessageFor(x => x.AssistanceRequestLastName)
#Html.TextBoxFor(x => x.AssistanceRequestLastName, new {#class = "form-control", required = "required"})
</div>
<div class="content-block__quarter-column">
#Html.LabelFor(x => x.AssistanceRequestPhoneNumber)
#Html.ValidationMessageFor(x => x.AssistanceRequestPhoneNumber)
#Html.TextBoxFor(x => x.AssistanceRequestPhoneNumber, new {#class = "form-control"})
</div>
<div class="content-block__quarter-column set-vertical-align-bottom">
<button id="btnSubmitAssistanceRequest" class="btn btn--primary">#Translation.Text("submit")</button>
</div>
</div>
</form>
Data Annotations
[RequiredLocalized, DisplayNameLocalized("first-name")]
public string AssistanceRequestFirstName { get; set; }
[RequiredLocalized, DisplayNameLocalized("last-name")]
public string AssistanceRequestLastName { get; set; }
[RequiredLocalized, DisplayNameLocalized("phone-required")]
[RegularExpressionLocalized(#"(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]‌​)\s*)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)([2-9]1[02-9]‌​|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})", "please-enter-a-valid-10-digit-phone-number", "Assistance")]
public string AssistanceRequestPhoneNumber { get; set; }
RequiredLocalized - Required attribute that returns a custom message. Works in other places of the site.
DisplayNameLocalized - DisplayName attribute with custom message. Works in other places.
Etc
This form is hidden by default and shown when the user clicks a certain button. Here are the scripts that are attached to the page:
<script src="/Scripts/jquery-1.8.3.min.js"></script>
<script src="/Scripts/jquery-ui-1.10.4.custom.min.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="/Scripts/jquery.validate.min.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="/Scripts/jquery.validate.extensions.js"></script>
<script src="/Scripts/Shared/jQueryGlobalSettings.js"></script>
Using Javascript to return false if there are errors on the page in this format:
$('#btnSubmitAssistanceRequest').click(function (e) {
var $answer = $('.js-title');
var $reqFirstName = $('#AssistanceRequestFirstName');
var $reqLastName = $('#AssistanceRequestLastName');
var $reqPhoneNumber = $('#AssistanceRequestPhoneNumber');
// Check for empty fields
if ($reqFirstName.val().trim() == "") {
showErrorMessage($reqFirstName, 'First Name is required.');
} else {
clearErrorMessage($reqFirstName);
}
if ($reqLastName.val().trim() == "") {
showErrorMessage($reqLastName, 'Last Name is required.');
} else {
clearErrorMessage($reqLastName);
}
if ($reqPhoneNumber.val().trim() == "") {
showErrorMessage($reqPhoneNumber, 'Phone Number is required.');
} else {
clearErrorMessage($reqPhoneNumber);
}
// check if validation errors were thrown
if ($(".field-validation-error").length) return false;
$.post('/api/[obfuscated]/[obfuscated]', { answer: $answer.text(), firstName: $reqFirstName.val(), lastName: $reqLastName.val(), phoneNumber: $reqPhoneNumber.val() }, function (data) {
if (data.success) {
$('.request-assistance-success').css('display', 'inline');
$(".feedback-container").slideUp(400);
} else {
$('.request-assistance-failure').css('display', 'inline');
$(".feedback-container").slideUp(400);
}
});
e.preventDefault();
return true;
});
Replace
<button id="btnSubmitAssistanceRequest" class="btn btn--primary">#Translation.Text("submit")</button>
with
<input type="submit" id="btnSubmitAssistanceRequest" class="btn btn--primary" Text="#Translation.Text("submit")"/>
Submit form invokes the unobtrusive validations.

how to enable a button in mvc razor based on radio button

I have the following code:
In Model:
<div class="line"></div>
<div class="clearfix"></div>
#Html.RadioButtonFor(x => x.Vehicle.Car, "Car")
#Html.LabelFor(x => x.Vehicle.Car)
<div class="clearfix"></div>
#Html.RadioButtonFor(x => x.Vehicle.Van, "Van")
#Html.LabelFor(x => x.Vehicle.Van)
<div class="line"></div>
<div class=".col-md-6 .col-sm-4 text-center">
<button type="button" class="btn btn-primary" disabled >submit</button>
</div>
I would like to enable the Submit button if either of the radio button is selected. Since using htmlhelper method, not sure of using Jquery method on it. Any help highly appreciated.
You can do this in client side. The below example assumes you have jQuery library included in your page.
Assuming your views' view model has a Vehicle property which is of type Vehicle enum like this
public enum Vehicle
{
None, Car, Van
}
public class CreateUser
{
public Vehicle Vehicle { set; get; }
// Other properties as needed
}
Give a css class to the radio button and and Id to the submit button for easier jQuery selection.
#model YourNamespaceHereForViewModelClass.CreateUser
#using (Html.BeginForm())
{
#Html.RadioButtonFor(x => x.Vehicle, "Car",new {#class="myVehicle"})
#Html.Label(Vehicle.Car.ToString())
#Html.RadioButtonFor(x => x.Vehicle, "Van", new { #class = "myVehicle" })
#Html.Label(Vehicle.Van.ToString())
<button type="button" id="mySubmit" class="btn btn-primary" disabled>submit</button>
}
and in your script, on the document ready event check whether any of the two radio buttons are checked and enable/disable the submit button. Also listen to the change event and enable the radio button.
$(function () {
// When the page loads,Check any radio button is checked, If yes enable submit button
if ($(".myVehicle:checked").length) {
$("#mySubmit").prop('disabled', false);
}
// When user checks a radio button, Enable submit button
$(".myVehicle").change(function (e) {
if ($(this).is(":checked")) {
$("#mySubmit").prop('disabled', false);
}
});
});
Here is a working js fiddle sample.

fluent validation validating a list of generated text boxes

I have set of textboxes on my form which are generated in a foeach like so:
View:
#for (int i = 0; i < Model.TransomeList.Count; i++)
{
ItemDrops tranItem = Model.TransomeList.ElementAt(i);
<div class="form-group">
#Html.Label(tranItem.ItemName.ToString(), new { #class = "col-sm-6 control-label" })
<div class="col-sm-6">
#Html.TextBoxFor(x => x.TransomeList[i].ItemPossInfo, new { #class = "form-control" })
#Html.HiddenFor(x => x.TransomeList[i].ItemName)
</div>
</div>
}
I'm using fluent validation and want to make sure each text box is required (ideally stating which text box too in the error message)
In my Validator class I have:
RuleFor(x => x.TransomeList).SetCollectionValidator(new TransDropValidator());
with:
public class TransDropValidator : AbstractValidator<ItemDrops>
{
public TransDropValidator()
{
RuleFor(x => x.ItemPossInfo)
.NotNull().WithMessage("Transom position required{O}", x => x.ItemPossInfo);
}
}
However this is not validating anything...what do i need to do?
Thanks
You also need the
#Html.ValidationMessageFor()
I assume you are doing server side validation. If not then futher work is need on your validator and you need to generate the JavaScript component.

Resources