How to Change label value on drp selected change event in MVC - asp.net-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

Related

Selecting all options in kendo multiselect

I have in my application a Kendo Multiselect component where I select my available options.
my View is like this:
div class="editor-field col-width45">
<div>
#(Html.Kendo().MultiSelectFor(model => model.FeaturesValues)
.DataTextField("Name")
.HtmlAttributes(new { #class = "size100Percent", Id = "FeaturesSelect" })
.DataValueField("Id")
.Placeholder("Selecione...")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetFeatures", "Role");
})
.ServerFiltering(false);
}))
</div>
</div>
I want to select all the options at once, and not be selecting one by one.
I looked for a way to do this and all the solutions brought me to this result:
I added a button in my View.
I created a Js function to select all:
my code stayed like this:
div class="editor-field col-width45">
<div>
#(Html.Kendo().MultiSelectFor(model => model.FeaturesValues)
.DataTextField("Name")
.HtmlAttributes(new { #class = "size100Percent", Id = "FeaturesSelect" })
.DataValueField("Id")
.Placeholder("Selecione...")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetFeatures", "Role");
})
.ServerFiltering(false);
}))
</div>
</br>
<div>
#(Html.Kendo().Button()
.Name("SelectAll")
.HtmlAttributes(new { type = "button" })
.Content("Selecionar todos")
.Events(ev => ev.Click("selectAll")))
</div>
JavaScript:
function selectAll() {
var multiSelect = $("#FeaturesSelect").data("kendoMultiSelect");
var selectedValues = [];
for (var i = 0; i < multiSelect.dataSource.data().length; i++) {
var item = multiSelect.dataSource.data()[i];
selectedValues.push(item.Id);
}
multiSelect.value(selectedValues);
multiSelect.trigger("change");
}
my result is this:
multiselect with button add all
Everything is working perfectly !!!
My question is:
Is it possible to create a checkbox inside the kendo Multiselect, to be used as select all, and not have this button?
What I want is something like this:
[multiselect without button][2]
enter image description here
You can add checkbox to header template which can be used to select - de select all elements.
Check this demo dojo
Though example here is shown using a Kendo UI JS, you can accomplish it using Kendo ASP.NET as well.
#(Html.Kendo().MultiSelect()
....
.HeaderTemplate("<label><input type='checkbox' id='selectAll'> Select All</label>")
I have prepared a quick dojo for you here. https://dojo.telerik.com/UpAFIdEx
This should hopefully be what you are after. I have just applied some simple styling just to get things looking a bit like your second image. but if you are using bootstrap or have css that handles positioning of elements this should work for you.
Any issues/questions let me know.

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
}
}

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.

DropDownListFor only selects first value

I have a details-view where a varying number of sites are displayed in textboxes. Next to each site the country should be shown in a disabled dropdown. My problem is that the dropdown does not select the right value. Instead it always selects the first item. Some debugging showed that "SelectedCountries[i]" is holding the correct value for each dropdown but somehow this value does not affect the selection at all.
The dropdown's names are "SelectedCountries[i]" and I've read it is bad to use the same name for the dropdown and for the field in the model. However, changing it didn't solve the problem.
<div id="allSitesAndCountries">
#for (int i = 0; i < Model.SelectedSites.Count; i++)
{
#Html.TextBoxFor(m => m.SelectedSites[i], new { disabled = "disabled", })
#Html.DropDownListFor(m => m.SelectedCountries[i], Model.AllCountriesSelectListItems, new{disabled = "disabled"})
}
</div>
What am I doing wrong here?
Thanks in advance.
EDIT: I got it working by creating the SelectList directly in the view and adding the 4th parameter:
<div id="allSitesAndCountries">
#for (int i = 0; i < Model.SelectedSites.Count; i++)
{
<div class="editor-label">
#Html.TextBoxFor(m => m.SelectedSites[i], new { disabled = "disabled"})
#Html.DropDownListFor(m => m.SelectedCountries[i], new SelectList(Model.AllCountries, "Id", "Name", Model.SelectedCountries[i]), new{disabled = "disabled"})
</div>
}
</div>

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