Combo Box selected value to javascript - javascript

In my ASP.NET MVC web application, I send some data to the combo box using the view bag from the controller to the view.
In the view, there is a javascript when the combo box value is changed, I send that value to the controller again using an ajax call and get the related data, and show it in another textbox.
ViewBag.Task_Assigned_Branch_Id = new SelectList(db.Branch.Where(x=>x.Status ==true), "Id", "BranchName");
View
<div class="form-group row">
#Html.LabelFor(model => model.Task_Assigned_Branch_Id, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.DropDownList("Task_Assigned_Branch_Id", null, "Select the Branch", new { #class = "form-control js-dropdown js-Branch", #Id = "Branch" })
#Html.ValidationMessageFor(model => model.Task_Assigned_Branch_Id, "", new { #class = "text-danger" })
</div>
</div>
Javascript
$('.js-Branch').change(function () {
GetBranchMembers($(this).val())
});
This worked perfectly.
Then I want to change it, when sending the data to the view bag, I wanted to select a default value to the combo box and send it to the view.
So I changed the controller code to
ViewBag.Task_Assigned_Branch_Id = new SelectList(db.Branch.Where(x=>x.Status ==true), "Id", "BranchName", branchId);
Now the value is loading as the default selected value in the combo box.
So to get the combo box value in the loading event I wrote this
$(document).ready(function ()
{
var e = document.getElementById("js-Branch");
alert(e);
GetBranchMembers(e)
})
But the id returns null.
I guess because I sent the default value to the combo box, it doesn't pass the id to the script or something. Is there any other way of doing this?

Try using below code. i think you are using wrong id. you are using a class name in getElementbyId function
$(document).ready(function ()
{
var e = document.getElementById("Branch");
alert(e);
GetBranchMembers(e)
});

Related

How to show dropdown list in the #Html.EditorFor() when user clicks on the text input box

I am passing data from the Controller to the View using the ViewData
Code in the controller:
public ActionResult Create()
{
ViewData["gN"] = new SelectList(db.gT, "id", "gN");
return View();
}
In the View I am using #Html.EditorFor() to create the new item for our table which we store in the database.
<div class="col-md-10">
#Html.EditorFor(model => model.gT.gN, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.groupid, "", new { #class = "text-danger" })
</div>
When I am using #Html.DropDownList our list of gN is perfectly showing as the dropdown list
#Html.DropDownList("gN", null, htmlAttributes: new { #class = "form-control" })
I want to use EditorFor() so that when the user starts typing in the input box, the dropdown list appears below it. and if that text which user is typing, present in the dropdown then the user can select it.
How we should show the list gN (which we are getting using ViewData from Controller) in the EditorFor() HTML element?
The Html.EditorFor() method always creates an <input> element, though the type attribute can vary depending on the model property type. HTML5 actually supports exactly what you want with the <datalist> element, which you tie to an <input> element with the list attribute. the <datalist> element takes child <option> elements containing the values you want in the list.
Making some guesses about your models here...
// Controller
public ActionResult Create()
{
ViewData["gN"] = db.gT;
return View();
}
// View
#Html.EditorFor(model => model.gT.gN, new { htmlAttributes = new { #class = "form-control", list="gN-datalist" } })
<datalist id="gn-datalist">
#foreach (var item in (gT)ViewData["gN"])
{
<option value="#item.id">#item.gN</option>
}
</datalist>
You could also create an HtmlHelper extension method that would create this for you.

Value from JQuery populated field not binding to MVC model

I'm working on a project with ASP.NET MVC, using Razor. Once the form finishes loading on the page, I expect the user triggers .on ('change') in an input. Once this happens, an AJAX call is executed, returning the user's data, disabling and filling the inputs that are linked to the properties of a model that starts empty (when the page is loaded).
The data is filling up without problems, but when I send it back to the controller to be processed, the values that correspond to the inputs that were filled after the AJAX execution arrive as null.
<div class="form-label-group col-md-4 mb-3">
#Html.LabelFor(model => model.AttendeeName, new { #class = "upside-label", #for = "firstName" })
#Html.EditorFor(model => model.AttendeeName, new { htmlAttributes = new { #class = "form-control", #id = "firstName", #placeholder = Resources.ResourcesPerson.PlaceholderPersonName } })
#Html.LabelFor(model => model.AttendeeName, new { #class = "downside-label", #for = "firstName" })
<div class="text-danger">
#Html.ValidationMessageFor(model => model.AttendeeName)
</div>
</div>
I have tried the following without success:
$("input[name=AttendeeName]").attr('disabled', true);
$("input[name=AttendeeName]").val(data.AttendeeName).change()
Thank you for your assistance.
This is expected behaviour. disabled elements are not sent in form data.
If you still want those values to be sent, don't disable the fields. Possibly try readonly instead, assuming that you don't want users to edit the fields:
$('input[name="AttendeeName"]').prop('readonly', true);

MVC #Html.DropDownListFor change displayed value in javascript

Using MVC 4, I am trying to change the displayed value in the view for #Html.DropDownListFor, based on the action of another drop down list. In the below example, when the user selects any value in the state list, I want the #Html.DropDownListFor to display the indexed 203 value which is US. How to do this?
//in the controller
ViewBag.statelist = new SelectList(db.states, "state_abbr", "state_name");
ViewBag.countrylist = new SelectList(db.countries, "country_id", "country_name", -1);
//in the View
<div class="form-group">
#Html.LabelFor(model => model.states)
#Html.DropDownList("ddlstate", ViewBag.statelist as SelectList, Model.rrq_sec1_waddr_stprov, htmlAttributes: new { #onchange="StateChange()" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.country)
#Html.DropDownListFor(model => model.country, ViewBag.countrylist as SelectList, "Select Country", htmlAttributes: new { #id="ddlcountry" })
</div>
//javascript
function StateChange() {
var state = document.getElementById("ddlstate").value;
$("#ddlcountry").val = 203;
};
How do I get the #ddlcountry index=203 which is "US" show up in view then the state drop down changes?
This might help u to select value in second dropdown, onchange event of first dropdown using this jQuery function.
$('#ddlstate').change(function () {
$("#ddlcountry").val( $('#ddlstate').val());
});

mvc dropdownlistfor validation run before submitting

I have an MVC 5 Application. I have a View that inherits from a Model View. I have a DropDownlistFor with Validation that cannot be empty.
The problem I have is that Validation executes as soon as I select an item from Dropdownlist. When I select the same First item "Choose a Country", I mean, y select the same default option, validation execute and show a Message "Country is required"...
I put an alert on jquery Submit button and on Controller Method and it does not reach that point.
Another curious thing is that this App is a Migration from Entity Framework to Enterprise Library Store Procedure ..
The Model that inherits the View is loaded on the Controller from Store Procedure instead of EntityFrawork.
This should be transparent to the View. But this error happens only in this versiĆ³n. It Works fine with Entity Framework.
Here is part of the code..
#model AvivaVozSP.Models.UserViewModel
#using System.Web.Mvc.Ajax
<form action="#Url.Action("Create", "Users")" id="form" enctype="multipart/form-data" method="post">
<div class="DvCampoUp">
#Html.DropDownListFor(m => m.user.Country_id, Model.AvailableCountries, new { #class = "StyleOb Required txtFill", #onclick = "ocultar();", #onchange = "javascript:GetState(this.value);", #id = "Country_id" })
</div>
<div class="DvCampoUp">
#Html.ValidationMessageFor(model => model.user.Country_id, "", new { #class = "text-danger" })
</div>
</form>
<script language="javascript" type="text/javascript">
$('form').submit(function (event) {
alert(1);
});
Any Ideas?
Use the default value like this
<div class="DvCampoUp">
#Html.DropDownListFor(m => m.user.Country_id, Model.AvailableCountries,"Choose a Country", new { #class = "StyleOb Required txtFill", #onclick = "ocultar();", #onchange = "javascript:GetState(this.value);", #id = "Country_id" })
</div>
and remove Choose a Country from the list

How to get selected value of dropdown when using partial view in mvc?

I am using partial view to display a view inside another and the partial view has the drodown so how to get the value of that dropdown actually i want to display another dropdown based on the value of the first dropdown here is my code in detail:
partial view:
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<link href="~/Content/control.css" rel="stylesheet" />
<fieldset>
<legend></legend>
<div class="editor-label">
#Html.LabelFor(model => model.CompanyID , new {#class="lbldis"})
</div>
<div class="editor-field">
#Html.DropDownListFor(Model => Model.CompanyID, new SelectList(ViewBag.CompanyList as System.Collections.IEnumerable, "_CompanyID", "Company"), "- Select -",new { #class = "txtbox",id="ddln" })
#Html.ValidationMessageFor(model => model.CompanyID)
</div>
<br />
<div>
#Html.DropDownListFor(Model => Model.ClientID, new SelectList(ViewBag.ClientList as System.Collections.IEnumerable, "_ClientID", "Company"), "- Select -",new { #class = "txtbox" })
#Html.ValidationMessageFor(model => model.ClientID)
</div>
</fieldset>
}
and the view where i am calling this partial view:and the name of that view is Index:
<div id="tab-1">
#Html.Partial("~/Views/PartialViews/_company.cshtml")
</div>
All the dropdowns are working fine and getting the values and all but only problem is with the javascript. Please help me on where to write the javascript i.e in partial view or in Index where I am calling my partial view and how to to display another dropdown based on the value of the first one.
What I have tried so far is below:
<script type="text/javascript">
$("#ddln").change(function onchange(dropdown) {
var myindex = dropdown.selectedIndex;
var SelValue = dropdown.options[myindex].value;
if (SelValue == 'Client3')
{
var see = document.getElementById("ddln");
see.style.display = "";
}
})
</script>
If you are using jquery you can handle controls of partial view from main view using on() function. Earlier (before 1.9) you could have used live() but this has been deprecated since.
$(document).ready(function () {
$('body').on("change", "#ddln", function (evt) {
if ($(this).val() != 'val1') //assume if val1 is the value against which we wish to show.
{
$('#ndl').show();
}
else
{
$('#ndl').hide();
}
});
});
To hide or display the 2nd dropdown based on a value in the first:
var clients = $('#ClientID');
$('#CompanyID').change(function() {
var id = $(this).val();
if (id == 'Client3') { // assume you want to hide it if the selected option value is 'Client3'
clients.hide();
} else {
clients.show();
}
});
Edit
Based on OP's last edit which changed the default id attribute from id="Company" to id="ddln", the code would be modified to
$('#ddln').change(function() { ...

Categories

Resources