MVC ajax dropdownlist url change - c#

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.

Related

Change view using ajax on drop-down list change event

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.

How to use AJAX on ASP.NET MVC RazorPage

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

how to show the data from the get method by calling it from jquery ajax?

I am developing an online Hotel Management system in asp[dot]net mvc. I have a list of items and each item has a checkbox in it which is for adding it to the order list whenever it is to be added. Problem is whenever I click "Add To Orders" button I get "error alert". I want Get Method of order controller to be called so that data in it should be shown in the view. Also check whether my post method is right or not?
<div class="form-group">
<div class="col-md-offset-2 col-md-2">
<input value="Add to Orders" class="btn btn-primary" onclick="submitItems()" />
#*<input id="submit" value="Place an Order" class="btn btn- primary" onclick="" />*#
</div>
</div>
<script>
//$('#submit').on('click', function (e) {
// e.preventDefault();
var submitItems = function () {
var arrItems = [];
var commaSepratedValues = "";
$("#itemList input[type=checkbox]").each(function (index, val) {
debugger;
var checkedId = $(val).attr("id");
var arr = checkedId.split("_");
var currentItemId = arr[1];
var isChecked = $("#" + checkedId).is(":checked", true);
if (isChecked) {
arrItems.push(currentItemId);
}
})
if (arrItems.length != 0) {
commaSepratedValues = arrItems.toString();
$.ajax({
url: "/Order/Create",
type: "GET",
data: { ItemList: commaSepratedValues },
success: function (data) {
alert('success');
},
error: function () { alert('error'); }
});
}
}
</script>
Above is the code where my function executes and then the problem arises.
Main Menu
Step 1
Step 2
step 3

Code first, Data is not inserting into database using cascading dropdown list

in my create [ Http post ] method, all data is inserting except the cascading drop down items. I have Department, Subject and section model. One department can have many subjects, one subject can have many sections. after adding jquery submit portion, it shows, form can not be submitted! then it returns to the index! here is my codes from Section Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Section section)
{
if (ModelState.IsValid)
{
db.Sections.Add(section);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "Name", section.DepartmentId);
ViewBag.SubjectId = new SelectList(db.Subjects, "SubjectId", "SubjectName", section.SubjectId);
return View(section);
}
Here is my create.chtml under Secion view:
#model MvcBCS.Models.Section
#{
ViewBag.Title = "Create Section";
}
#section scripts {
<script type="text/javascript">
$(function() {
$.getJSON("/Section/Departments/List", function(data) {
var items = "<option> Show Department List </option>";
$.each(data, function(i, department) {
items += "<option value='" + department.Value + "'>" + department.Text + "</option>";
});
$("#Departments").html(items);
});
$("#Departments").change(function() {
$.getJSON("/Section/Subjects/List/" + $("#Departments > option:selected").attr("value"), function(data) {
var items = "<option> Show Subject List </option>";
$.each(data, function(i, subject) {
items += "<option value='" + subject.Value + "'>" + subject.Text + "</option>";
});
$("#Subjects").html(items);
});
});
});
$(function() {
$('#submit').on("click", function () {
var form = $(this).parent("form");
$.ajax({
type: "POST",
url: form.attr('action'),
data: form.serialize()
})
.success(function() {
alert("Your form has been submitted");
})
.error(function() {
alert("Your form has not been submitted");
});
return false;
});
});
</script>
}
<h2>Create Section</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Section</legend>
<label for="Departments">Departments</label>
<select id="Departments" name="Departments"></select>
<label for="Subjects">Subjects</label>
<select id="Subjects" name="Subjects"></select>
<label for="Sections">Section</label>
<input id="Sections" name="Sections" type="text" />
<p>
<input type="submit" id="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
I think you need to change the name/Id of your both dropdownlist regarding your properties in your section.
For Departments to DepartmentId and Subjects to SubjectId. They need to match with so in your Post the binder will attach the correct value

Getting a local variable value using jQuery

I have a little problem when trying to get the value of a local int variable on a view, using jQuery. So, I have a the main view, and as you can see in the code below, I use a partial view named "_Result", when I try to get the value of indexPage by handling the click event of a button in the partial view, I get 0, event if I initialize my variable by another value(5 for example). Any idea why ?
Thanks in advance
My view :
#model System.Data.DataTable
#{var pageIndex = 5;}
<div>
<div>
<span>Téléphone ?</span>
<input id="idTxTel" type="text" name="txTelephone"/>
<input id="idBnSearch" type="submit" value="Chercher" name="bnSearch"/>
</div>
#Html.Partial("_Result", Model)
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#idBnSearch").click(function () {
//The right value (5)
alert('#pageIndex');
var telValue = $("#idTxTel").val();
var methodUrl = '#Url.Content("~/Search/GetReverseResult/")';
'#{pageIndex = 0;}'
doReverseSearch(telValue, '#pageIndex', methodUrl);
});
$("#bnNextPage").live("click", function ()
{
//Not th right value (0)
alert('#pageIndex');
});
});
</script>
My doReverseSearch method :
function doReverseSearch(telValue, pageIdx, methodUrl)
{
$.ajax(
{
url: methodUrl,
type: 'post',
data: JSON.stringify({ Telephone: telValue, pageIndex: pageIdx }),
datatype: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('#result').replaceWith(data);
},
error: function (request, status, err) {
alert(status);
alert(err);
}
});
}
My partial view :
<div id="result">
<h2>Résultat de la recherche</h2>
<div>#ViewBag.CountResult entreprises trouvées</div>
#if(Model != null)
{
foreach (DataRow row in Model.Rows)
{
<h3>#row["CompanyName"]</h3>
}
}
<hr />
<div>
<span>Page N sur M</span>
<input id="bnPreviousPage" type="submit" value="Précédant" name="bnPrevious"/>
<input id="bnNextPage" type="submit" value="Suivant" name="bnNext"/>
</div>
</div>
Razor inside javascript has to be wrapped in a block
so you can do this:
<script>
// global value for page
<text>
var myPage = #pageIndex;
<text>
</script>
what would be far easier is give the button an attribute of data-page and ask for attribute in click event:
<button data-page="#("pageIndex")" id="myButt" />
$("#myButt").on("click",function(e){
var pageIndex = $(this).attr("data-page");
alert(pageIndex);
});

Categories