I am trying to create a cascading DropDownList on ASP.NET RazorPage. After doing some research I found the most common way to do the task is utilizing jQuery in my View. Nearly all demos and examples I found online implement a cascading DropDownList in previous ASP.NET versions, more specifically MVC. I tried translating these examples in the context of how I need them but I am having no luck, most likely due to syntax errors and/or other reasons.
I am using ASP.NET Core 2.2
I am having trouble specifically implementing the dynamic function call (GetSubCategory) whenever an item is selected in the first DropDownList which is displaying correctly
<form asp-controller="my_dropdown" asp-action="CreatePortfolio" method="post" class="form-horizontal" role="form">
<div class="form-group">
<div class="row">
<div class="alert-danger" asp-validation-summary="ModelOnly"></div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4">
<label for="CategoryName">Category</label>
#Html.DropDownList("categorylist",
new SelectList((System.Collections.IEnumerable)ViewData["categorylist"], "CategoryId", "CategoryName"), "Select Category", "CategoryName")
<label for="SubCategoryName">Subcategory</label>
#section scripts{
<script type="text/javascript">
//Insert default item "Select" in dropdownlist on load
$(document).ready(function () {
var items = "<option value='0'>Select</option>";
$("#colorselect").html(items);
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#CategoryId").on("change", function () {
$list = $("#SubCategory");
$.ajax({
type: "GET",
url: '/CreatePortfolio',
data: { id: $("#CategoryId").val() },
traditional: true,
success: function (response) {
$list.empty();
$.each(result, function (i, item) {
$list.append('<option value="' + item["SubCategoryId"] + '"> ' + item["SubCategoryName"] + '</option>');
});
},
error: function () {
alert("Something went wrong"); // Hide loader icon
},
});
})
})
</script>
}
</div>
</div>
</div>
Code behind the view
public JsonResult GetSubCategory(int CategoryId)
{
subcategorylist = _context.GetAllSubCategories(CategoryId);
//ViewData["subcategorylist"] = subcategorylist;
return new JsonResult(subcategorylist);
}
public void OnGet()
{
// ----- Getting Data From Database Using Stored Procedure -----
categorylist = _context.GetAllCategoires();
// ----- Assigning categorylist to ViewData["categorylist"] in order to access it in the view -----
ViewData["categorylist"] = categorylist;
}
I want the code to correctly display the SubCategories associated to the Category by CategoryId which is a field in both classes/tables
Related
I need to change the view in same page using ajax when the user changes the option of the drop-down list.
Up until now in my view I have the drop down list
<div class="wrapper">
<div>
<label>Get cars per people </label>
#Html.DropDownList("ddlChange", new SelectList(ViewBag.OptionsList,"Value","Text", ViewBag.selectedValue),new { #id = "ddlChangeID" })
</div>
<div class="box box-success">
<div class="box-body">
<div>
<canvas id="myChart"></canvas>
</div>
</div>
</div>
</div>
Then in a script (which I found from another question)
$(document).ready(function () {
$("#ddlChangeID").change(function () {
var strSelected = "";
$("#ddlChangeID:selected").each(function () {
strSelected += $(this)[0].value;
});
var url = "/Cars/Index/" + strSelected;
$.post(url, function (data) {
});
});
})
And in the controller I am using ViewBag values to save the drop-down list values and whatever else is needed for the graph which loads in a different script again with ViewBag values. I have managed to pass the selected value (strSelected) but the view does not reload with the new data.
How should I make the ajax event?
Change your script ajax call by calling an action result as follows
$("#ddlChangeID").change(function () {
$.ajax({
url: "/Controller/ActionHtml?id="+$('#ddlChange').val(),
type: "POST",
cache: false,
success: function (result) {
$("#myChart").html(result);
},
error: function () {
$("#myChart").empty();
}
});
});
and in the controller the actionresult will be like the following which returns the html partial view that you need to append
public ActionResult ActionHtml(string id)
{
//Here you can load the data based on the id,pass model to the patial views etc
ViewBag.id = id;
return PartialView("~/Views/Shared/myhtml.cshtml");
}
myhtml.cshtml will be a partial view with the html content as
//content is dummy,change the content as you want
<!DOCTYPE html>
<html>
<body>
<p>Enter some text in the fields below, then press the "Reset form" button to reset the form.</p>
<form id="myForm">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
</form>
So I changed the
#Html.DropDownList("ddlChange", new SelectList(ViewBag.OptionsList,"Value","Text", ViewBag.selectedValue),new { #id = "ddlChangeID" })
To
#Html.DropDownList("ddlChange", new SelectList(ViewBag.OptionsList,"Value","Text", ViewBag.selectedValue),new { #onchange = "ChangeOption()" })
adding also an id to the main div.
And the script to
function ChangeOption() {
var id = $('#ddlChange').val();
$.ajax({
url: '/Cars/Index',
type: "GET",
data: { Id: id },
success: function (data) {
$('#wrapAll').html(data);
}
});
}
It seems to work. Only issue now is that the css breaks.
It pushes the graph and drop-down list to the right breaking
the functionality.
I was comparing a webgrid and a dropdownbox .I want to trigger a partial view CoursePartialDemo via Ajax and has to pass the primary key to the action responsible for partialview.In a dropdownbox i have successfully done it by following Jquery.Similarly if i select a row in a webgrid how can i trigger partial view and pass the primary key which is "id" for webgrid.following code is responsible for dropdownbox
<select id="ddlEmployeeCourse">
#*Iterating Employee ViewModel *#
#foreach (var emp in Model)
{
<option value="#emp.EmpCode">#emp.EmpName</option>
}
</select>
<h4>Courses Of Selected Employeee</h4>
<div id="CoursesForEmp">
</div>
<script>
function getCourseTable(selectedEmpCode) {
$.ajax({
// Get Course PartialView
url: "/Home/CoursePartialDemo",
type: 'GET',
data: { EmpCode: selectedEmpCode },
success: function (data) {
jQuery("#CoursesForEmp").html(data);
},
error: function (error) {
alert("Error: Please try again.");
}
});
}
</script>
<script>
jQuery(document).ready(function () {
jQuery("#ddlEmployeeCourse").change(function (index) {
var selectedEmpCode = $(this).val();
getCourseTable(selectedEmpCode);
});
</script>
and here is my webgrid code
<div id="">
#grid.GetHtml(tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
selectedRowStyle: "select",
columns: grid.Columns(
//grid.Column("Id", format: (item) => item.GetSelectLink(item.Id)),
grid.Column("id", "id"), //primary key
grid.Column("countryname", format: (item) => item.GetSelectLink(item.countryname)),
grid.Column("continent", "Description", style: "continent"),
grid.Column("language", "language")
))
</div>
UPDATE
i have done some changes in webgrid code like shown below
#if (grid.HasSelection)
{
product = (firstmvc4.Models.Country)grid.Rows[grid.SelectedIndex].Value;
var val = #product.id;
<script>
getCourseTable(val)
</script>
}
but javascript function is triggering at all
Change
<script>
getCourseTable(val)
</script>
to
Html.RenderAction("CoursePartialDemo", new { EmpCode = val });
and place inside the CoursesForEmp element.
For example:
<div id="CoursesForEmp">
#if (grid.HasSelection)
{
product = (firstmvc4.Models.Country)grid.Rows[grid.SelectedIndex].Value;
var val = product.id;
Html.RenderAction("CoursePartialDemo", new { EmpCode = val });
}
</div>
I'm not sure if you want to show any product details or employee.
I'm trying to implement the select2 on my master layout of my ASP.NET MVC 4 website.
I want it to, as soon as the user starts typing (minimum of 2 letters), call my method to query the database using the letters the user has already typed. Except, when I start typing, my method never gets called. I threw in some alerts and I'm able to see what I'm typing, but the select2 isn't firing, I think.
Here's the script and css references in the tag:
<script src="/Content/select2/select2.js"></script>
<link href="/Content/select2/select2.css" rel="stylesheet" />
Here's the search box in my layout.cshtml file:
<div class="navbar-header hidden-xs pull-right" style="padding-top: 10px; margin-left: 10px;">
<input id="search" class="form-control" placeholder="Search..." type="text" data-autocomplete-url="/Home/AutoFillValues" />
</div>
And here's the bottom of my layout page where the select2 stuff appears:
<script src="/Scripts/jquery-1.9.1.min.js"></script>
<script src="/Scripts/bootstrap.min.js"></script>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
#RenderSection("scripts", required: false)
<script type="text/javascript">
$(document).ready(function () {
$("#search").select2({
placeholder: "Search...",
minimumInputLength: 2,
ajax: {
url: "~/Home/AutoFillSearch",
dataType: 'jsonp',
data: function(search) {
return {
q: search
};
},
results: function(search, page) {
return { results: data.Results };
}
}
});
});
</script>
Lastly, here's my controller method (I'm not worried about the code here yet, I just want to see my breakpoint get hit at the first line...):
public ActionResult AutoFillValues()
{
// Get all wrestlers and all teams
var players = _playerRepo.Query().Where(w => w.Division == "Division I" && w.Conference != null);
var schools = players.Select(w => w.School).Distinct();
ArrayList list = new ArrayList();
foreach (var school in schools)
{
var hyperlinkFormat = "{1}";
//#HttpUtility.UrlEncode(Model.Team.Name, System.Text.Encoding.UTF8)
list.Add(string.Format(hyperlinkFormat, string.Format(RosterPath, school), string.Format(RosterText, school)));
}
foreach (var player in playerss)
{
var hyperlinkFormat = "{1}";
//#HttpUtility.UrlEncode(Model.Team.Name, System.Text.Encoding.UTF8)
list.Add(string.Format(hyperlinkFormat, string.Format(RosterPath, player.School), string.Format(RosterText, player.School)));
}
return Json(list.ToArray());
}
I had to upgrade to jQuery 2.1 (because of the issue with version 1.9 and the .live/.on functions) in order for my select2 to start firing.
Now I just need to get my select2 styled...
I have few dropdownlist created by using Html.DropDownListFor like:
<div class="control-group">
<label class="control-label" for="inputPropertySurname">
City
<span class="form-required" title="This field is required.">*</span>
</label>
<div class="controls">
#*<input type="text" id="inputPropertySurname">*#
#Html.DropDownListFor(m => m.CityId, vmpa.Cities)
</div>
<!-- /.controls -->
</div>
but it always create a div area after selectbox
<div id="CityId_chzn" class="chzn-containerchzn-container-single
chzn-container-single-nosearch" style="width: 220px;" title="">
<a href="javascript:void(0)" class="chzn-single" tabindex="-1">
<span>Hà Nội</span>
<div><b></b></div>
</a>
<div class="chzn-drop" style="left: -9000px;">
<div class="chzn-search"><input type="text" autocomplete="off">
</div>
<ul class="chzn-results">
<li id="CityId_chzn_o_0" class="active-resultresult-selected" style="">Hà Nội</li>
<li id="CityId_chzn_o_1" class="active-result" style="">Hồ Chí Minh</li>
</ul>
</div>
</div>
i use ajax to get json array and replace new option in json aray to dropdownlist. select box have new option but it still show old option in div id City_chzn. i try many ways jquery but can't refresh it to show new value.
my ajax
<script type="text/javascript">
$(document).ready(function () {
$("#CountryId").chosen().change(function () {
var id = $("#CountryId option:selected").val();
DDLCountryChange(id);
});
});
function DDLCountryChange(id) {
var ddl = $("#CityId");
ddl.chosen();
ddl.prop("disabled", true);
$.ajax({
url: "/Post/GetCityInfoByCountry/" + id,
type: "GET",
dataType: "JSON",
success: function (result) {
ddl.empty();
var str = '';
$.each(result, function (index, value) {
ddl.chosen().append("<option value='" + value['Value'] + "'>" + value['Text'] + "</option>");
ddl.chosen().trigger('listzt:updated');
});
//ddl.prop('disabled', false);
}
});
}
</script>
UPDATE
Now i know why my code create a div. because my template using chosen jquery so it is reason why a div created after select. my chosen ver 0.9.12. i'm using
ddl.trigger('listzt:updated');
but chosen doesn't update new value to display
UPDATE
I have solved my problem. trigger('liszt:updated') not listzt:updated. All my bad :(
Please take a look at this very descriptive and helpful tutorial on how to work with DropDownLists, in an MVC environment, using JQuery and JSON rest services.
http://www.c-sharpcorner.com/UploadFile/4b0136/working-with-dropdownlist-in-mvc-5/
Strangely, the example they are using to make the tutorial, is almost exactly what you're doing here (Country, City, etc)...
Hope this helps!
I am new in ajax and I need a help.
This is a script that populates second dropdownlist once first is selected.
It works fine using GetStates action that gets data from database.
<script type="text/javascript">
$(document).ready(function () {
$("#CountriyID").change(function () {
var abbr = $("#CountriyID").val();
$.ajax({
url: "/SetUp/GetStates",
data: { countryCode: abbr },
dataType: "json",
type: "POST",
error: function () {
alert("An error occurred.");
},
success: function (data) {
var items = "";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
});
$("#StateID").html(items);
}
});
});
});
</script>
Here is the view that I am working on
#using (Html.BeginForm("Index", "SetUp", FormMethod.Post))
{
<form action="" method="post">
<input type="submit" name="action:AddCity" value="Add" />
</form>
<div class="editor-field">#Html.DropDownListFor(model => model.CountriyID, new SelectList(Model.Countries, "ID", "Text"))</div>
<div class="editor-field">#Html.DropDownListFor(model => model.StateID, new SelectList(Model.States, "ID", "Text"))</div>
}
If I need to add a City I click on a submit button and it goes to correct action.
The problem happened when I populate dropdownlist. After population, the City button do not respond anymore. It looks like the url get stack at "/SetUp/GetStates" and I cannot do any actions anymore on my form.
Please Let me know what am I doing wrong and where to take a look?
Thanks in advance.
try the below code hope it helps you:
<form action="" method="post">
<div class="editor-field">#Html.DropDownListFor(model => model.CountriyID, new SelectList(Model.Countries, "ID", "Text"))</div>
<div class="editor-field">#Html.DropDownListFor(model => model.StateID, new SelectList(Model.States, "ID", "Text"))</div>
<input type="submit" name="action:AddCity" value="Add" />
</form>
As the drop down must come into the tags and submit must be at the last place in the tags ideally.