Trying to save the customer details using AngularJS - c#

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()
};
...

Related

asp.net Razor Pages - Update select list based on the selection of another select list

I want to update a select list when the user selects a value in another select list. I've managed to get the first select list to call a get (or post) method on the model with a parameter, and can update the underlying data. But the second select list never shows the new values.
I'm not very experienced with asp.net, so what am I doing wrong?
Code below
.cshtml
<div>
<form method="post">
<select id="departureStation" asp-items="Model.DepartureStations" onchange="getDestinationStations()"></select>
<select id="destinationStation" asp-items="Model.DestinationStations"></select>
</form>
</div>
#section Scripts {
<script type="text/javascript">
function getDestinationStations() {
var selectedDepartureStationID = $("#departureStation").find(":selected").val();
console.log("selectedDepartureStationID = " + selectedDepartureStationID);
$.ajax({
type: "GET",
url: "/Index?handler=Departure",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
selectedDepartureStationID: selectedDepartureStationID
},
success: function(result) {
console.log("success - " + result);
},
error: function() {
console.log("failure");
}
})
}
</script>
}
.cs
public List<SelectListItem> DestinationStations
{
get
{
if (this._selectedDepartureStationID == -1)
return new List<SelectListItem>();
List<Models.Station> stations = new List<Models.Station>();
List<Models.RouteSegment> routeSegments = this._context.RouteSegments.Where(x => x.StationID == this._selectedDepartureStationID).ToList();
foreach (Models.RouteSegment routeSegment in routeSegments.DistinctBy(x => x.RouteID))
{
List<Models.RouteSegment> routeSegments2 = this._context.RouteSegments.Where(x => x.RouteID == routeSegment.RouteID).Include(x => x.Station).ToList();
stations.AddRange(routeSegments2.Select(x => x.Station));
}
return new List<SelectListItem>(stations.Distinct().ToList().Select(x => new SelectListItem { Value = x.StationID.ToString(), Text = x.StationName }).ToList());
}
}
public IndexModel(MyViewContext context)
{
this._context = context;
}
public void OnGet()
{
this.DepartureStations = this._context.Stations.Select(x => new SelectListItem { Value = x.StationID.ToString(), Text = x.StationName }).ToList();
}
public IActionResult OnGetDeparture(int selectedDepartureStationID)
{
this._selectedDepartureStationID = selectedDepartureStationID;
return Page();
}
Whenever your #departureStation select changes, your code will call getDestinationStations javascript code. Inside that function you are sending a request to your backend server to receive possible destination stations if I understood correctly. What you need to do here is when ajax request successes, add options dynamically based on your returned array or data.
I am assuming your "/Index?handler=Departure" returns a JSON like:
[
{
id: 1,
name: "station1"
},
{
id: 2,
name: "station2"
}
]
Check if code below works.
$.ajax({
type: "GET",
url: "/Index?handler=Departure",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
selectedDepartureStationID: selectedDepartureStationID
},
success: function(result) {
let destinationStationSelect = $('#destinationStationSelect');
let optionTemplate = $('<option></option>');
$.each(result, (index, element) => {
let option = optionTemplate.clone();
option.append(element.name);
option.attr('value', element.id);
destinationStationSelect.append(option);
});
},
error: function() {
console.log("failure");
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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>

Get selectedIndex of dropdown using c# (Razor)

Is it possible to get the selectedIndex of a dropdown in a view using C# (Razor). For example, can I fill a second dropdown based off the selectedIndex of another dropdown using Razor?
#model ViewModel
<select id="dropdown1">
//Options
</select>
<select id="dropdown2">
//Options
</select>
#if(//The selectedIndex of dropdown1 == 4)
{
//Fill dropdown 2 from model
}
When using Javascript, I am a little off as well:
<script>
if (dropdown1.selectedIndex === 3)
{
#foreach (var item in Model)
{
}
}
</script>
You can do it using a ajax call when the first dropdown changes:
<script type="text/javascript">
function getDropDown2Data(id) {
$.ajax({
url: '#Url.Action("GetDropDown2Data", "YourController")',
data: { Id: id },
dataType: "json",
type: "POST",
success: function (data) {
var items = "";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Name + "\">" + item.Id + "</option>";
});
$("#dropDown2").html(items);
}
});
}
$(document).ready(function () {
$("#dropDown2").change(function () {
var id = $("#dropDown2").val();
getDropDown2Data(id);
});
});
</script>
#Html.DropDownListFor(x => x.Id, new SelectList(Model.Model1, "Id", "Name"), "Select")
#Html.DropDownListFor(x => x.Id, new SelectList(Model.Model2, "Id", "Name"), "Select")
And you action:
[HttpPost]
public ActionResult GetDropDown2Data(id id)
{
//Here you get your data, ie Model2
return Json(Model2, JsonRequestBehavior.AllowGet);
}

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/

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

#{
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

Categories