my javascript code not working(debugger not going inside get method) - c#

#{
ViewBag.Title = "Index";
Layout = null;
}
<h2>Index</h2>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Country State City Bind </title>
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
$(function ()
{
//******* code for state bind with countryid…………..
$("#ddlcountry").change(function () {
//debugger;
//$(this).closest('tr').remove();
var v2 = $(this).val();
$.get("DropdownTest/StateBind", { country: v2 }, function (data) {
$("#state").empty();
var v = "<option>Select</option>";
$.each(data, function (i, v1) {
v += "<option value='" + v1.Value + "'>" + v1.Text + "</option>";
});
$("#state").html(v);
});
});
//******* code for city bind with stated……………………
$("#state").change(function () {
var v2 = $(this).val();
$.get("DropdownTest/CityBind", { state: v2 }, function (data) {
$("#city").empty();
var v = "<option>Select</option>";
$.each(data, function (i, v1) {
v += "<option value='" + v1.Value + "'>" + v1.Text + "</option>";
});
$("#city").html(v);
});
});
});
</script>
</head>
<body>
<div>
<table>
<tr><td colspan="2"><font color="Red">Bind Json Result to DropDownlist in MVC4 Country State City Concept</font></td></tr>
<tr><td>Country Name</td><td>#Html.DropDownList("ddlcountry", "Select" )</td></tr>
<tr><td>State Name</td><td><select id="state"><option>Select</option></select></td></tr>
<tr><td>City Name</td><td><select id="city"><option>Select</option></select></td></tr>
</table>
</div>
</body>
</html>
enter code here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCDropdownlist.Dal;
namespace MVCDropdownlist.Controllers
{
public class DropdownTestController : Controller
{
//
// GET: /DropdownTest/
harshalEntities ctx = new Dal.harshalEntities();
public ActionResult Index()
{
ViewBag.ddlcountry = CountryBind();
return View();
}
//code for bind Country Name...........................
public List<SelectListItem> CountryBind()
{
List<SelectListItem> li = new List<SelectListItem>();
foreach (var v in ctx.Countries)
{
li.Add(new SelectListItem { Text = v.CountryName, Value = v.CountryId.ToString() });
}
//ViewBag.ddlcountry = li;
//return View();
return li;
}
//code for bind State Name...........................
public JsonResult StateBind(string country)
{
int id = Convert.ToInt32(country);
var v = ctx.States.Where(m => m.CountryId == id).Select(m => new { Text = m.StateName, Value = m.StateId });
return Json(v, JsonRequestBehavior.AllowGet);
}
//code for bind City Name...........................
public JsonResult CityBind(string state)
{
int id = Convert.ToInt32(state);
var v = ctx.Cities.Where(m => m.StateId == id).Select(m => new { Text = m.CityName, Value = m.CityId });
return Json(v, JsonRequestBehavior.AllowGet);
}
}
}
my function not going inside get method

Related

C# Mvc Web Api Cascading List

This is my controller.
public class DokuzasController : Controller
{
public ActionResult AddOrEdit()
{
DersViewModel model = new DersViewModel();
schoolEntities sc = new schoolEntities();
List<ders> dersList = sc.ders.OrderBy(f => f.Ders1).ToList();
model.DersList = (from s in dersList
select new SelectListItem
{
Text = s.Ders1,
Value = s.DersID.ToString()
}).ToList();
model.DersList.Insert(0, new SelectListItem { Value = "", Text = "Select"});
return View(model);
}
[HttpPost]
public ActionResult AddOrEdit(DersViewModel model)
{
if (model.LectureId == 0)
{
HttpResponseMessage response = GlobalVariables.LecturesClient.PostAsJsonAsync("dokuzas", model).Result;
TempData["SuccessMessage"] = "Saved.";
}
else
{
HttpResponseMessage response = GlobalVariables.LecturesClient.PutAsJsonAsync("dokuzas/" + model.LectureId, model).Result;
TempData["SuccessMessage"] = "Successful.";
}
return RedirectToAction("Index");
}
[HttpPost]
public JsonResult SaatList(int id)
{
schoolEntities sc = new schoolEntities();
List<saat> saatList = sc.saat.Where(f => f.DersID == id).OrderBy(f => f.Saat1).ToList();
List<SelectListItem> itemList = (from i in saatList
select
new SelectListItem
{
Value = i.SaatID.ToString(),
Text = i.Saat1
}).ToList();
return Json(itemList, JsonRequestBehavior.AllowGet);
}
}
And this is my AddOrEdit file.
#model Mvc.Models.DersViewModel
#{
ViewBag.Title = "AddOrEdit";
}
#using (Html.BeginForm("AddOrEdit", "Dokuzas", FormMethod.Post))
{
#Html.DropDownListFor(m => m.DersID, Model.DersList)
<br /><br />
#Html.DropDownListFor(m => m.SaatID, Model.SaatList)
<br />
<input type="submit" value="Kaydet" class="btn button" />
}
#section scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#DersID").change(function () {
var id = $(this).val();
var saatList = $("#SaatID");
saatList.empty();
$.ajax({
url: '/Dokuzas/SaatList',
type: 'POST',
dataType: 'json',
data: { 'id': id },
success: function (data) {
$.each(data, function (index, option) {
saatList.append('<option value=' + option.Value + '>'
+ option.Text + '</option>')
});
}
});
});
});
</script>
}
I have a table and this table contains Dersadi and Dagilimi properties. I wanted to create a cascading list and add to table from this list from DersList to Dersadi and from SaatList to Dagilimi. But i choose items and select submit button i can submit it but it added null to the table. It did not add what i choose from the list. How can i fix this?
in the view, you can use the DropDownList helper method to render the SELECT element with the data we set to the Model.DersList. We will also add our second dropdown as well.
#using (Html.BeginForm("AddOrEdit", "Dokuzas", FormMethod.Post))
{
#Html.DropDownList("DersID", Model.DersList as SelectList)
<select name="id" id="SaatID" data-url="#Url.Action("SaatList","Home")">
<br />
<input type="submit" value="Kaydet" class="btn button" />
}
<script type="text/javascript">
$(function(){
$("#DersID").change(function (e) {
var $SaatID = $("#SaatID");
var url = $SaatID.data("url")+'?id='+$(this).val();
$.getJSON(url, function (items) {
$.each(items, function (a, b) {
$vacancy.append('<option value="' + b.Value + '">' + b.Text + '</option>');
});
});
});
});
</script>

MVC controller query

Following is my cascasde dropdown list query. Countries list loading up but non of the states loading up in my dropdown list. if someone can help me to rectify the query please.
public ActionResult CountryList()
{
var countries = db.Countries.OrderBy(x=>x.CountryName).ToList();
// IQueryable countries = Country.GetCountries();
if (HttpContext.Request.IsAjaxRequest())
{
return Json(new SelectList(
countries,
"CountryID",
"CountryName"), JsonRequestBehavior.AllowGet
);
}
return View(countries);
}
public ActionResult StateList(int CountryID)
{
IQueryable <State> states= db.States. Where(x => x.CountryID == CountryID);
if (HttpContext.Request.IsAjaxRequest())
return Json(new SelectList(
states,
"StateID",
"StateName"), JsonRequestBehavior.AllowGet
);
return View(states);
}
following is the View file also containg java script:
#section scripts {
<script type="text/javascript">
$(function () {
$.getJSON("/Dropdown/Countries/List",function (data) {
var items = "<option>---------------------</option>";
$.each(data, function (i, country) {
items += "<option value='" + country.Value + "'>" + country.Text + "</option>";
});
$("#Countries").html(items);
});
$("#Countries").change(function () {
$.getJSON("/Dropdown/States/List/" + $("#Countries > option:selected").attr("value"), function (data) {
var items = "<option>---------------------</option>";
$.each(data, function (i, state) {
items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
});
$("#States").html(items);
});
});
});
</script>
}
<h1>#ViewBag.Title</h1>
#using (Html.BeginForm())
{
<label for="Countries">Countries</label>
<select id="Countries" name="Countries"></select>
<br /><br />
<label for="States">States</label>
<select id="States" name="States"></select>
<br /><br />
<input type="submit" value="Submit" />
}
First of all, your action method name is StateList which expects a parameter named CountryID. But your code is not making a call to your StateList action method with such a querystring param. So fix that.
$("#Countries").change(function () {
$.getJSON("#Url.Action("StateList","Home")?CountryID=" +
$("#Countries").val(), function (data) {
var items = "<option>---------------------</option>";
$.each(data, function (i, state) {
items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
});
$("#States").html(items);
});
});
I also used #Url.Action helper method to get the correct url to the action method with the assumption that your StateList action method belongs to HomeController. Update the parameter according to your real controller name as needed.
Now, In your action method, you should not try to return the IQueryable collection, you may simply project the data to a list of SelectListItem and return that.
public ActionResult StateList(int CountryID)
{
var states = db.States.Where(x => x.CountrId==CountryID).ToList();
//this ToList() call copies the data to a new list variable.
var stateOptions = states.Select(f => new SelectListItem {
Value = f.StateID.ToString(),
Text = f.StateName }
).ToList();
if (HttpContext.Request.IsAjaxRequest())
return Json(stateOptions, JsonRequestBehavior.AllowGet);
return View(states);
}

Trying to save the customer details using AngularJS

I am working on an MVC application and I can not understand why I am getting few values as 'null'.
What should be done to serialize the date value from JavaScript to C#.
View code:
#{
Layout = null;
}
<!DOCTYPE html>
<html ng-app="mvcCRUDApp">
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module("mvcCRUDApp", []);
app.service("crudAJService", function ($http) {
// save Customer
this.saveCustomer = function (objCustomer) {
var response = $http({
method: "post",
url: "Customer/PostDataResponse",
data: JSON.stringify(objCustomer),
dataType: "json"
});
return response;
}
});
app.controller("mvcCRUDCtrl", function ($scope, crudAJService) {
$scope.AddCustomer = function () {
var objCustomer = {
id: "0",
Name: $('#txtName').val(),
Surname: $('#txtSurname').val(),
BirthDate: $('#txtBirthDate').val(),
Gender: $('#txtGender').val(),
CityId: $('#drpCity').val()
};
var getBookData = crudAJService.saveCustomer(objCustomer);
getBookData.then(function (msg)
{
alert(msg.data);
}, function () {
alert('Error in updating book record');
});
}
});
</script>
<script>
$(document).ready(function ()
{
$("#drpState").change(function () {
$("#drpCity").empty();
$("#drpCity").append('<option value="0">-Select-</option>');
$.ajax({
type: 'POST',
url: '#Url.Action("SelectCities")',
dataType: 'json',
data: { Stateid: $("#drpState").val() },
success: function (cities) {
// cities contains the JSON formatted list
// of state id passed from the controller
$.each(cities, function (i, city)
{
$("#drpCity").append('<option value="'
+ city.id + '">'
+ city.Name + '</option>');
});
},
error: function (ex)
{
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
</head>
<body>
<div ng-controller="mvcCRUDCtrl">
<fieldset>
<table>
<tr><td>#Html.Label("Name")</td><td>#Html.TextBox("txtName")</td><td>#Html.Label("Surname")</td><td>#Html.TextBox("txtSurname")</td></tr>
<tr><td>#Html.Label("BirthDate")</td><td>#Html.TextBox("txtBirthDate")</td><td>#Html.Label("Gender")</td><td>#Html.TextBox("txtGender")</td></tr>
<tr>
<td>State</td>
<td>#Html.DropDownList("drpState", ViewBag.StateCollection as List<SelectListItem>)</td>
<td>City</td>
<td>#Html.DropDownList("drpCity", ViewBag.CityCollection as List<SelectListItem>)</td>
</tr>
<tr><td><input type="submit" value="Submit" ng-click="AddCustomer()" /></td></tr>
</table>
</fieldset>
</div>
</body>
</html>
Following is THE CODE OF CONTROLLER
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DutchProject.Models;
namespace DutchProject.Controllers
{
public class CustomerController : Controller
{
DutchEntities db = new DutchEntities();
//
// GET: /Customer/
public ActionResult Index()
{
List<SelectListItem> States = new List<SelectListItem>();
var lstStates = db.States.ToList();
States.Add(new SelectListItem { Text = "-Select-", Value = "0" });
foreach (var item in lstStates)
{
States.Add(new SelectListItem { Text = item.Name, Value = item.id.ToString() });
}
ViewBag.StateCollection = States;
List<SelectListItem> Cities = new List<SelectListItem>();
Cities.Add(new SelectListItem { Text = "-Select-", Value = "0" });
ViewBag.CityCollection = Cities;
return View();
}
[HttpPost]
public JsonResult SelectCities(int Stateid)
{
IEnumerable<City> cities = db.Cities.Where(stat => stat.StateId == Stateid); // .Where(stat => stat.country_id == id);
return Json(cities);
}
[HttpPost]
public ContentResult PostDataResponse(Customer objCustomer)
{
objCustomer.BirthDate = DateTime.Now;
objCustomer.Gender = 1;
db.Customers.Add(objCustomer);
db.SaveChanges();
return Content("First name: " + Request.Form["firstName"] +
" | Last name: " + Request.Form["lastName"] +
" | Age: " + Request.Form["age"]);
}
}
}
ASP.NET MVC passes a null value in the controller action for a value that is not valid. It may help to validate the date beforehand, just to be sure the value is valid.
Also, it might help to assign a date instead of string:
...
var objCustomer = {
id: "0",
Name: $('#txtName').val(),
Surname: $('#txtSurname').val(),
BirthDate: new Date($('#txtBirthDate').val()),
Gender: $('#txtGender').val(),
CityId: $('#drpCity').val()
};
...

drop down list refresh in razor

I have a drop down list which represent states and according to selected state, I need to refresh City drop down list which represent the cities in the selected state. How can I refresh the city drop down ?
Here is my code :
public class AccountController : Controller
{
public static List<SelectListItem> StateListItem()
{
var stateList = new List<SeraydarBL.Accounts.State>();
var selectListItems = new List<SelectListItem>();
stateList = SeraydarBL.Accounts.SelectStates();
foreach (var state in stateList)
{
var selectListItem = new SelectListItem();
selectListItem.Text = state.name;
selectListItem.Value = state.id.ToString();
selectListItems.Add(selectListItem);
}
return selectListItems;
}
}
here is the razor :
#using (Html.BeginForm())
{
<fieldset>
<legend>Registration Form</legend>
<ol>
<li>
//-------------------------------------------------------
var stateList = new List<SelectListItem>();
stateList = AccountController.StateListItem();
}
#Html.LabelFor(model => model.StateId)
#Html.DropDownListFor(model => model.StateId, stateList, " Select your State ...")
#Html.ValidationMessageFor(m => m.StateId)
#*HERE MUST BE THE DROP DOWN LIST OF CITIES*#
</li>
</ol>
<input type="submit" value="Register" />
</fieldset>
<script>
$('#StateId').change(function () {
});
</script>
}
You can achieve this using jquery ajax call.
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#StateId").change(function () {
$("#CityId").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetCity")',
dataType: 'json',
data: { id: $("#StateId").val() },
success: function (cities) {
$.each(cities, function (i, city) {
$("#CityId").append('<option value="' + city.Value + '">' +``});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
refer few articles
http://www.codeproject.com/Articles/730953/Cascading-Dropdown-List-With-MVC-LINQ-to-SQL-and-A
http://www.c-sharpcorner.com/UploadFile/4d9083/creating-simple-cascading-dropdownlist-in-mvc-4-using-razor/

Cascading Dropdownlist is not working with Jquery

I have to do one dropdownlist and one listbox. When I select a value in dropdownlist, the listbox has to change. I'm trying to do this with Jquery, because I'm using MVC. But when I select the ID in the first dropdownlist, nothing happens. My code:
View (Jquery):
<script type="text/javascript">
$(document).ready(function () {
$('#IDCONCESSAO').change(function () {
$.ajax({
url: '/Localidades/LocalidadesMunicipio',
type: 'POST',
data: { ConcessaoId: $(this).val() },
datatype: 'json',
success: function (data) {
var options = '';
$.each(data, function () {
options += '<option value="' + this.IdLocalidade + '">' + this.NomeLocalidades + '</option>';
});
$('#IDLOCALIDADE').prop('disabled', false).html(options);
}
});
});
});
</script>
Dropdownlist and listbox part:
<%: Html.DropDownListFor(model => model.SINCO_CONCESSAO, new SelectList(ViewBag.IDCONCESSAO, "Id", "Nome"), new { #class = "select", style = "width: 250px;" }) %>
</div>
<div class="editor-label" style="font-weight: bold">
Localidades:
</div>
<div class="editor-field" id="Localidades">
<%: Html.ListBoxFor(m => m.SelectedItemIds, Model.ItemChoices, new { id = "IDLOCALIDADE", size = "10" })%>
</div>
The action that do the cascade:
[HttpPost]
public ActionResult LocalidadesMunicipio(int ConcessaoID)
{
var Localidades = (from s in db.LOCALIDADES_VIEW
join c in db.SINCO_CONCESSAO.ToList() on s.ID_MUNICIPIO equals c.IDMUNICIPIO
where c.IDCONCESSAO == ConcessaoID
select new
{
idLocalidade = s.ID_LOCALIDADE,
NomeLocalidades = s.NOME_LOCALIDADE
}).ToArray();
return Json(Localidades);
}
Controller:
[Authorize(Roles = "ADMINISTRADOR")]
public ActionResult Create(SINCO_LOCALIDADE_CONCESSAO model)
{
//Here I populate my dropdownlist
ViewBag.IDCONCESSAO = from p in db.SINCO_CONCESSAO.ToList()
join c in db.MUNICIPIOS_VIEW.ToList() on p.IDMUNICIPIO equals c.ID_MUNICIPIO
join d in db.SINCO_TIPO_CONCESSAO.ToList() on p.IDTIPOCONCESSAO equals d.IDTIPOCONCESSAO
select new
{
Id = p.IDCONCESSAO,
Nome = p.IDCONCESSAO + " - " + c.NOME_MUNICIPIO + " - " + d.DSTIPOCONCESSAO
};
//Here I populate my listbox
PopulateItemLocalidades(model);
return View(model);
}
I can't see what is wrong T_T
What I am missing?
The first drop down most likely has an ID of SINCO_CONCESSAO, by the name of the property it was created for. And you are referring to something different in your script.
To fix this, either specify a different ID in jQuery:
$('#SINCO_CONCESSAO').ajax ...
or set an ID for a dropdown in View:
<%: Html.DropDownListFor(model => model.SINCO_CONCESSAO, ...
, new { id = "IDCONCESSAO" ... }) %>

Categories