radiobutton to display message - asp.net-mvc

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.

Related

ASP.NET MVC - How to Specify the Value in TextBox

How do I specify the Value that should be entered into the Textbox. I dont want to use dropdownlist. I want to accept only these three (3) values Nigeria, Ghana and Togo
If any other value is entered it should not save or hide or disable the Save button.
View
<div class="col-md-12">
<div>
#Html.LabelFor(model => model.COUNTRY_NAME, "Country Name")
#Html.TextBoxFor(model => model.COUNTRY_NAME, new { #style = "border-radius:3px;", #type = "text", #class = "form-control", #placeholder = "Country Name", #autocomplete = "on" })
#Html.ValidationMessageFor(model => model.COUNTRY_NAME, null, new { #class = "text-danger" })
</div>
</div>
Please how do I achieve this?
There are two Options
You can use Server side Custom Validator for Country_Name property.
Or Jquery validation on client side.
When you submit the form, you can validate textbox value by jQuery.
<button onclick="validateData();"></button>
Then write a validation method as follows.
function validateData() {
if (Nigeria, Ghana and Togo) {
//ajax post to your controller
} else {
//return error message
}
}

MVC html helpers change hiddenfor attributes

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.

How to Change label value on drp selected change event in MVC

I have below code and I want to change label text base on selected role.
For example, If I select Admin then in label Text I need "Admin Name" etc.
I use below code but I is not working.
<div class="editor-field">
#Html.DropDownListFor(model => model.RoleID, new SelectList(ViewBag.RoleLsit, "Id", "RoleName"), "Select Category", new { onchange = "SelectedIndexChanged()" })
</div>
<div>
#Html.LabelFor(model => model.RoleName)
#Html.EditorFor(model => model.RoleName)
#Html.ValidationMessageFor(model => model.RoleName)
</div>
<script type="text/javascript">
function SelectedIndexChanged() {
var sub = document.getElementsByName("RoleName");
sub.value = "Selected Role Name";
}
Thanks
You could find your elements using #Html.IdFor, if your js is in your view.
function SelectedIndexChanged() {
//find the label
var label = document.querySelector('label[for="#Html.IdFor(m => m.RoleName)"]');
//get the dropDown selected option text
var dropDown = document.getElementById("#Html.IdFor(m => m.RoleId)");
var selectedText = dropDown.options[dropDown.selectedIndex].text;
//set the label text
label.innerHTML=selectedText
}
By the way, taking a look a jQuery might be an "interesting" option.
You could simply remove the new { onchange = "SelectedIndexChanged()" , then
$('##Html.IdFor(m => m.RoleId)').change(function() {
$('label[for="#Html.IdFor(m => m.RoleName)"]').text($(this).children('option:selected').text());
});
function SelectedIndexChanged() {
document.getElementsById("RoleName").InnerHtml="Role name goes here";
}
you should use get element by id instead of name because when this html helper renders the strongly typed binded attributes becomes the id of that control . so in your case role name will be the ID

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.

Enabling the second and third dropdownlistfor based on the value of first dropdownlistfor in MVC

I have three DropDownLists. If a specific Value from my first DropDownList is chosen, the second Dropdownlist should be enabled. Example, if "Player 3" has been choosen, the other two DropDownList should be enabled, though, if "Player 2" is chosen the last DropDownList should be disabled and the second one enabled.
How can I easily do this? I am using MVC 3 EF model first.
This is my code in my view:
<p>Player</p>
<div class="editor-field">
#Html.DropDownListFor(m => m.PlayerName,Model.SubjectTypes, "Choose player" , new { #class = "selectstyle" })
#Html.ValidationMessageFor(model => model.PlayerName)
</div>
<p>Position</p>
<div class="editor-field">
#Html.DropDownListFor(model => model.PositionName, Model.Consultants, "Choose Position", new { #class = "selectstyle" })
#Html.ValidationMessageFor(model => model.ContactPerson)
</div>
<p>Team</p>
<div class="editor-field">
#Html.DropDownListFor(model => model.TeamName, Model.Teams, "Choose Team", new { #class = "selectstyle" })
#Html.ValidationMessageFor(model => model.ContactPerson)
</div>
I would do the following in jquery:
$('#PlayerName').change(function()
{
var id = $(this).val()
$.ajax({
url: '#Url.Action("GetPositions")',
data:
{
"id": id,
},
success: function (data)
{
$("#positions").html(data);
}
});
}
Then i will have in the action controller:
public JsonResult GetPositions(int id)
{
var positions = Repository.GetPositionsByPlayerId(id);
var hmtl = positions.Select(x => new SelectListItem
{
Value = x.PositionID.ToString(),
Text = x.Name
});
return new JsonResult { Data = html };
}
This will fill the values with all the postions related to that player.
You could subscribe to the .change() event of the first dropdown and then based on the currently selected value enable/disable the others:
$(function() {
$('#PlayerName').change(function() {
var value = $(this).val();
if (value == 'Player3') {
$('#PositionName, #TeamName').removeAttr('disabled');
} else if (value == 'Player2') {
$('#PositionName').removeAttr('disabled');
$('#TeamName').attr('disabled', 'disabled');
}
});
});

Resources