calling a button through javascript ASP.NET MVC dropdown list - javascript

I want to call a HTML button through a JavaScript function that responds on a drop down list change. But for some reason it's not finding the correct id.
#using (Ajax.BeginForm("GetReport", "Choices",
new AjaxOptions() {
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET",
UpdateTargetId = "reportResults",
}
)) {
#Html.DropDownList("q",(IEnumerable<SelectListItem>)ViewData["YearTermList"], htmlAttributes: new { #class = "form-control" })
<br />
#Html.DropDownList("ChartList", null, htmlAttributes: new { #class = "form-control" })
<br />
<input type="submit" style="display:none" id="ShowList" value="Search"/>
}
<script type="text/javascript">
$(document).ready(function () {
$("#YearTermList").change(function () {
$("#ShowList").click();
});
});
</script>
The JavaScript function doesn't submit the button on the drop down list change.

Selector $("#YearTermList") finds nothing, because the is no id YearTermList in markup.
You should either add id="YearTermList" where you want to add listener or change the selector of listener from #YearTermList to #q, #ChartList or other.

Related

Combo Box selected value to 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)
});

Dynamically adding Partial View using Ajax

I have created a partial view where i am using Bootstrap Glyphicon (collapse and expand) upon button click. But, the JavaScript code is not working here as I am
dynamically adding Partial View using Ajax.
My Controller:
public ActionResult DisplaySearchResults(int Id)
{
if (Id == 317)
{
return PartialView("~/Views/Shared/_PartialReportViews/StatisticalReport.cshtml");
}
else if (Id == 318)
{
return PartialView("~/Views/Shared/_PartialReportViews/Leading_Progeny.cshtml");
}
return PartialView();
}
My main View:
<div class="container">
<div id="partial"></div>
#section scripts{
<script type="text/javascript">
$('.search').click(function () {
var id = $(this).data('assigned-id');
var route = '#Url.Action("DisplaySearchResults", "Home")?id=' + id;
$('#partial').load(route);
});
var partial = $('#partial');
partial.on('shown.bs.collapse', '.collapse', function () {
$(this).closest('.group').find(".glyphicon-plus").removeClass("glyphicon-plus").addClass("glyphicon-minus");
}).on('hidden.bs.collapse', '.collapse', function () {
$(this).closest('.group').find(".glyphicon-minus").removeClass("glyphicon-minus").addClass("glyphicon-plus");
});
</script>
}
<input class="search btn-info" type="button" value="Search" data-assigned-id="#item.ProductId" />
</div>
My Partial View
<div class="group">
<button type="button" value="Button" data-toggle="collapse" data-target="#demo">
<span class="glyphicon glyphicon-plus"></span>
</button>
<div class="container">
<div class="row">
<div class=" col-sm-12">
#using (Html.BeginForm("Report", "Home", FormMethod.Get))
{
#Html.DisplayNameFor(m => m.Name)
#Html.TextBoxFor(m => m.Name, new { #class = "form-control", style = "width: 155px", placeholder = Html.DisplayNameFor(n => n.Name})
#Html.HiddenFor(m => m.Id)
}
</div>
<div id="demo" class="collapse">
<div class="col-sm-12">
#Html.DisplayNameFor(model => model.StartDate)
#Html.TextBoxFor(m => m.StartDate, new { #class = "form-control", style = "width: 155px", placeholder = Html.DisplayNameFor(n => n.StartDate) })
#Html.DisplayNameFor(model => model.Distance)
#Html.DropDownListFor(m => m.Distance, Model.DistanceOptions, "All", new { #class = "form-control", style = "width: 150px;" })
</div>
</div>
</div>
</div>
</div>
Can anyone please guide me where I am going wrong?
I believe you need to add the event listeners to the button instead. This appears to work.
$('#demo').on('shown.bs.collapse', function () {
debugger;
$(this).parent().prev('button').find(".glyphicon-plus").removeClass("glyphicon-plus").addClass("glyphicon-minus");
}).on('hidden.bs.collapse', function () {
debugger;
console.log('hide');
$(this).parent().prev('button').find(".glyphicon-minus").removeClass("glyphicon-minus").addClass("glyphicon-plus");
});
And here is a link to fiddle that simply outputs 'show' or 'hide' to your console.log to show that it does indeed work.
https://jsfiddle.net/wuvrp0y3/
Edit for clarification:
You may need to change the selectors used within the functions, as the context of $(this) is no longer valid.
After comments;
It appears that you are calling the $(document).ready function only once, on page load (as you should be), and the -new- partial view does not have the events registered.
I would suggest creating a function that sets up those events (also turning off those events beforehand, as so;
function SetUpCollapse(){
$('.collapse').off('click shown.bs.collapse hidden.bs.collapse');
//This is necessary to prevent multiple calls from triggering this event multiple times.
$('.collapse').on('click', 'shown.bs.collapse', function () {
debugger;
$(this).parent().prev('button').find(".glyphicon-plus").removeClass("glyphicon-plus").addClass("glyphicon-minus");
}).on('hidden.bs.collapse', function () {
debugger;
console.log('hide');
$(this).parent().prev('button').find(".glyphicon-minus").removeClass("glyphicon-minus").addClass("glyphicon-plus");
});
}
Then, in your document.ready, call it;
$(document).ready(function(){
SetUpCollapse();
});
I assume you use ajax to load your partial view. However you do that, there should be an 'on completion' function, simply call that same function within that as well.
IE,
$.ajax({
url: "SomeURLHere",
type: "POST",
data: {data: data},
dataType: "html",
success: function (html) {
//append html
SetUpCollapse();
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
Are your event listeners possibly missing an event?
from
$('.collapse').on('shown.bs.collapse', function () {
to
$('.collapse').on('click', '.shown.bs.collapse', function () {

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() { ...

Does JavaScript get excuted when partial view is loaded?

Background
I'm working with ASP.NET MVC. I've got a partial view which contains JavaScript. I'm using AJAX get to load the partial view into a <div> tag. The JavaScript registers a click event for a group of radio buttons.
Problem
It doesn't seem to be executing: when the radio buttons are clicked, the form doesn't get submitted.
Here is my partial view:
<% using (Ajax.BeginForm(ActionName.Approve, ControllerName.Supervisor, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "Result"}, new { id = "IsSupervisorApprovalRequiredForm" }))
{%>
<p>Is supervisor approval required?</p>
<label for="IsSupervisorApprovalRequired">Yes</label><%=Html.RadioButton("IsSupervisorApprovalRequired", "0", new { #class = "IsSupervisorApprovalRequiredYes" })%>
<label for="IsSupervisorApprovalRequired">No</label><%=Html.RadioButton("IsSupervisorApprovalRequired", "1", new { #class = "IsSupervisorApprovalRequiredNo" })%>
<%} %>
<script type="text/javascript">
$("#IsSupervisorApprovalRequired").click(function() {
$("form#IsSupervisorApprovalRequiredForm").submit();
});
</script>
Question
Does JavaScript get executed when partial view is loaded?
Yes and no. The order of execution in your scenario is as follows:
Page gets requested
ASP.NET Renders Partial View into the parent page
Javascript gets executed on that entire page
For your particular problem. You'll need to load that Javascript snippet on page load before it can actually bound to the events. Your code should look like the following:
<% using (Ajax.BeginForm(ActionName.Approve, ControllerName.Supervisor, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "Result"}, new { id = "IsSupervisorApprovalRequiredForm" }))
{%>
<p>Is supervisor approval required?</p>
<label for="IsSupervisorApprovalRequired">Yes</label><%=Html.RadioButton("IsSupervisorApprovalRequired", "0", new { #class = "IsSupervisorApprovalRequiredYes" })%>
<label for="IsSupervisorApprovalRequired">No</label><%=Html.RadioButton("IsSupervisorApprovalRequired", "1", new { #class = "IsSupervisorApprovalRequiredNo" })%>
<%} %>
<script type="text/javascript">
$(function() {
$("#IsSupervisorApprovalRequired").click(function() {
$("form#IsSupervisorApprovalRequiredForm").submit();
});
});
</script>
Wrap the statement in $(function() {...}); so it will get called when the document is ready.
So it would look something like this:
$(function() {
$("#IsSupervisorApprovalRequired").click(function() {
$("form#IsSupervisorApprovalRequiredForm").submit();
});
});
This might also be caused by the HTML generated by the HtmlHelper. Multiple HTML elements with the same ID are not allowed, but the helper will generate something like:
<input id="IsSupervisorApprovalRequired" name="IsSupervisorApprovalRequired" type="radio" />
<input id="IsSupervisorApprovalRequired" name="IsSupervisorApprovalRequired" type="radio" />
As a result, when you match "#IsSupervisorApprovalRequired" with jQuery, it's looking for an element with that ID. Since two of them exist, the function will only be bound to the first one, causing the second radio button's "click" event to never fire.
As an alternative, try this:
$("input[name=IsSupervisorApprovalRequired]").click(function () { /* ... */ });
This approach checks the "name" attribute of the element instead of its ID. Since "name" values, unlike IDs, don't have to be unique, jQuery is able to handle multiple elements matching that pattern and should bind the event correctly.

Categories

Resources