cascading dropdown in angular with key relation between them - angularjs

I have country and state dropdowns.Country and state has relation on countryid.
I am getting an error while fetching data for these two cascading dropdowns.
Below is the image of error on controller returning JsonResult for countries.
Angular function:
var getdata = fac.GetCountry = function () {
return $http.get('/Data/GetCountries')
};
getdata.then(function (d) {
$scope.CountryList = d.data;
}, function (error) {
alert('Error!');
});
Controller:
public JsonResult GetCountries()
{
List<Country> allCountry = new List<Country>();
using (SunilEntities dc = new SunilEntities())
{
allCountry = dc.Countries.OrderBy(a => a.CountryName).ToList();
}
return new JsonResult { Data = allCountry, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
//return Json(allCountry, JsonRequestBehavior.AllowGet);
}
View:
<div ng-controller="dropdowns">
Country : <select ng-model="CountryID" ng-options="I.CountryID as I.CountryName for I in CountryList" ng-change="GetState()">
<option value="">Select Country</option>
</select>
State : <select ng-model="StateID" ng-options="I.StateID as I.StateName for I in StateList">
<option value="">{{StateTextToShow}}</option>
</select>
<input type="button" value="Get Selected Values" ng-click="ShowResult()"/>
<div style="padding:10px; font-weight:bold; border:1px solid #f3f3f3">
{{Result}}
</div>
</div>
Models:
public partial class Country
{
public Country()
{
this.States = new HashSet<State>();
}
public int CountryID { get; set; }
public string CountryName { get; set; }
public virtual ICollection<State> States { get; set; }
}
public partial class State
{
public int StateID { get; set; }
public string StateName { get; set; }
public Nullable<int> CountryID { get; set; }
public virtual Country Country { get; set; }
public virtual State State1 { get; set; }
public virtual State State2 { get; set; }
}
public DbSet<Country> Countries { get; set; }
public DbSet<State> States { get; set; }

I got the soltution.
BY changing actions (controller) a bit i got the the results.
Controller:-
public JsonResult GetCountries()
{
using (SunilEntities dc = new SunilEntities())
{
var ret = dc.Countries.Select(x => new { x.CountryID, x.CountryName }).ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
}
// Fetch State by Country ID
public JsonResult GetStates(int countryID)
{
using (SunilEntities dc = new SunilEntities())
{
var ret = dc.States.Where(x => x.CountryID == countryID).Select(x => new { x.StateID, x.StateName }).ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
}
I have country and state dropdowns.Country and state has relation on coutryid.
I am getting an error while fetching data for these two cascading dropdowns.
Below is the image of error on controller returning JsonResult for countries.
Angular funtion:-
var getdata= fac.GetCountry = function () {
return $http.get('/Data/GetCountries')
};
getdata.then(function (d) {
$scope.CountryList = d.data;
}, function (error) {
alert('Error!');
});
View:-
<div ng-controller="dropdowns">
Country : <select ng-model="CountryID" ng-options="I.CountryID as I.CountryName for I in CountryList" ng-change="GetState()">
<option value="">Select Country</option>
</select>
State : <select ng-model="StateID" ng-options="I.StateID as I.StateName for I in StateList">
<option value="">{{StateTextToShow}}</option>
</select>
<input type="button" value="Get Selected Values" ng-click="ShowResult()"/>
<div style="padding:10px; font-weight:bold; border:1px solid #f3f3f3">
{{Result}}
</div>
</div>
Models:-
public partial class Country
{
public Country()
{
this.States = new HashSet<State>();
}
public int CountryID { get; set; }
public string CountryName { get; set; }
public virtual ICollection<State> States { get; set; }
}
public partial class State
{
public int StateID { get; set; }
public string StateName { get; set; }
public Nullable<int> CountryID { get; set; }
public virtual Country Country { get; set; }
public virtual State State1 { get; set; }
public virtual State State2 { get; set; }
}
public DbSet<Country> Countries { get; set; }
public DbSet<State> States { get; set; }

Related

Want to create dropdown list from another table in blazor server with sql server

I already making my database table in my SQL Server.
The tables are:
Here's my ApplicationDbContext.cs :
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options):base(options)
{
}
public DbSet<ProjectModel> ProjectTB { get; set; }
public DbSet<TaskModel> TaskTB { get; set; }
}
ProjectModel.cs :
public class ProjectModel
{
[Key]
public int ProjectId { get; set; }
public string? ProjectName { get; set; }
}
TaskModel.cs :
public class TaskModel
{
[Key]
public int TaskId { get; set; }
public string? TaskName { get; set; }
public int? TimerQuantity { get; set; }
public int? ProjectId { get; set; }
public string? Note { get; set; }
}
ProjectServices.cs :
public class ProjectServices
{
private readonly ApplicationDbContext _dbcontext;
public ProjectServices(ApplicationDbContext _db)
{
_dbcontext = _db;
}
public List<ProjectModel> GetProjectModels()
{
return _dbcontext.ProjectTB.ToList();
}
TaskService.cs :
public class TaskServices
{
private readonly ApplicationDbContext _dbcontext;
public TaskServices(ApplicationDbContext _db)
{
_dbcontext = _db;
}
public List<TaskModel> GetTaskModels()
{
return _dbcontext.TaskTB.ToList();
}
}
I already populate some project name in my project table, so when I create this page (project page):
#page "/bindingddl"
#using TestUntukDropdown.Data
#using TestUntukDropdown.Services
#inherits OwningComponentBase<ProjectServices>
<h3>Ddlbinding</h3>
<br />
<hr />
<h4>This is from table ProjectTB</h4>
<select>
<option selected disabled="true">-- Select Project --</option>
#foreach(var item in projectobj)
{
<option title="#item.ProjectName">#item.ProjectName</option>
}
</select>
#code {
List<ProjectModel> projectobj;
protected override void OnInitialized()
{
projectobj = Service.GetProjectModels();
}
}
The output is:
I want to populate my dropdown list for my task table that refer to project table, so when I edit project name for my task, I can choose it from the project name in project table.
So when I click the dropdown of project name in my task page:
It populated from the project table's project name.
Here's my task page:
#page "/bindingddltask"
#using TestUntukDropdown.Data
#using TestUntukDropdown.Services
#inherits OwningComponentBase<TaskServices>
<h3>Ddlbinding</h3>
<br />
<hr />
<h4>This is from table TaskTB</h4>
<select>
<option selected disabled="true">-- Select Project --</option>
#foreach(var item in taskobj)
{
<option title="#item.ProjectId">#item.ProjectId</option>
}
</select>
#code {
List<TaskModel> taskobj;
protected override void OnInitialized()
{
taskobj = Service.GetTaskModels();
}
}

Access the Property of foreign key table in the view of other table using MVC and Entity framework

How do we access the Property of Resume from JobPostActivity to the view of
CandidateDetail ?
//CandidateDetail
namespace CarrerPage
{
using System;
using System.Collections.Generic;
public partial class CandidateDetail
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage",
"CA2214:DoNotCallOverridableMethodsInConstructors")]
public CandidateDetail()
{
this.JobPostActivitys = new HashSet<JobPostActivity>();
}
public int RID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailID { get; set; }
public string PHONENUMBER { get; set; }
public int Experience { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage",
"CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<JobPostActivity> JobPostActivitys { get; set;
}
}
}
//JobPostActivity
namespace CarrerPage
{
using System;
using System.Collections.Generic;
public partial class JobPostActivity
{
public int Id { get; set; }
public int RID { get; set; }
public Nullable<int> CandidateID { get; set; }
public Nullable<int> JobID { get; set; }
public Nullable<System.DateTime> Applydate { get; set; }
public string RESUME { get; set; }
public byte[] FileContent { get; set; }
public virtual CandidateDetail CandidateDetail { get; set; }
}
}
//Upload
<div class="form-group">
#Html.LabelFor(model=>model., htmlAttributes: new {
#class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="files" required />
#Html.ValidationMessageFor(model=> model.)
</div>
</div>
https://www.itsolutions-inc.com/news-and-training/article/entity-framework-6-database-first-versus-code-first/
near that model how to access the Resume property in candidateDetail?

I am getting 'System.Data.Entity.Infrastructure.DbUpdateConcurrencyException' .....when i tried to update a row in my table

i am trying to update a specific row in my table but i get An exception of type 'System.Data.Entity.Infrastructure.DbUpdateConcurrencyException' occurred in EntityFramework.dll but was not handled in user code
{"Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions."}
my action method is
public ActionResult createedit()
{
int id = Convert.ToInt32( Session["UserID"]);
var Certtt = (from cert in db.TBL_UserRegistration where cert.UserLoginID == id select cert).FirstOrDefault();
TBL_UserRegistration u = db.TBL_UserRegistration.Find(Certtt.UserRegistrationID);
return View(u);
}
[HttpPost]
public ActionResult createedit(TBL_UserRegistration user, HttpPostedFileBase imageup)
{
if(imageup != null)
{
user.UserImage = new byte[imageup.ContentLength];
imageup.InputStream.Read(user.UserImage, 0, imageup.ContentLength);
}
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return View(user);
}
my view
#using (Html.BeginForm("createedit", "UserRegistration", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<form class="wiwet-checkout">
<div class="row">
<div class="col-sm-6">
<!-- <input type="text" placeholder="First Name" />-->
#*#Html.LabelFor(model => model.UserFirstName, htmlAttributes: new { #class = "text-label", #placeholder = "Password" })*#
#Html.EditorFor(model => model.UserFirstName, new { htmlAttributes = new { #class = "form-control", #placeholder = "First Name" } })
#Html.ValidationMessageFor(model => model.UserFirstName, "")
</div>
.
.
.
}
my model TBL_UserResgistration is
public partial class TBL_UserRegistration
{
public TBL_UserRegistration()
{
this.TBL_Payment = new HashSet<TBL_Payment>();
}
public int UserRegistrationID { get; set; }
public Nullable<System.DateTime> UserRegistrationDate { get; set; }
public string Username { get; set; }
public string UserPassword { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
public string UserEmail { get; set; }
public string UserType { get; set; }
public string UserCity { get; set; }
public string UserState { get; set; }
public string UserCountry { get; set; }
public Nullable<int> UserZip { get; set; }
public string UserAddressLine1 { get; set; }
public string UserAdressLine2 { get; set; }
public Nullable<long> UserPhone1 { get; set; }
public Nullable<long> UserPhone2 { get; set; }
public byte[] UserImage { get; set; }
public Nullable<int> UserLoginID { get; set; }
public virtual TBL_Login TBL_Login { get; set; }
public virtual ICollection<TBL_Payment> TBL_Payment { get; set; }
}
You are getting this exception because entity framework can't find your user object in the database to update it READ MORE, that's because you are passing a user entity with only first name as I can see from your view, what you can do is this, pass your id as a hidden field, get user model by id from you database context, set the new user first name, update, done.
this is how you do it
in your view, pass the id as hidden
#using (Html.BeginForm("createedit", "UserRegistration", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<!-- here is the hidden field keeping your id -->
#Html.Hidden("UserRegistrationID ",Model.UserRegistrationID )
<form class="wiwet-checkout">
<div class="row">
<div class="col-sm-6">
<!-- <input type="text" placeholder="First Name" />-->
#*#Html.LabelFor(model => model.UserFirstName, htmlAttributes: new { #class = "text-label", #placeholder = "Password" })*#
#Html.EditorFor(model => model.UserFirstName, new { htmlAttributes = new { #class = "form-control", #placeholder = "First Name" } })
#Html.ValidationMessageFor(model => model.UserFirstName, "")
</div>
.
.
.
}
in your controller
// get the real entity from the database using the id passed to your controller
// as i mentioned before you should keep it in a hidden field
TBL_UserRegistration u = db.TBL_UserRegistration.Find(user.UserRegistrationID);
// update the entity user name according to the new one passed from your view
u.UserFirstName = user.UserFirstName;
// update and save
db.Entry(u).State = EntityState.Modified;
db.SaveChanges();

Angularjs Model passing null to MVC controller

The following code is sending null object to MVC controller from Angularjs controller. In the "batarang" $scope is displaying EmployeeInfo object with proper values fill in HTML form. But MVC method is getting all values null. My code is as below
Controller :
Angular.module("myApp", []).controller("EmployeeBasicCtrl", function ($scope, $http) {
$scope.signBox = false;
$scope.SEX = [
{ text: "Non of above", value: "N" },
{ text: "Female", value: "F" },
{ text: "Male", value: "M" },
]
$scope.submitBasicInfo = function () {
$http({
method: 'POST',
url: '/EmployeeInfo/AddEmployee'
}).success(
function (resp) {
$scope.success = resp.success;
$scope.Message = resp.Message;
}
)// success en
} // end of submit form
})// end of controller
HTML:
<form ng-submit="submitBasicInfo()" name="EmployeeBasic" ng-controller="EmployeeBasicCtrl">
<div class="well">
<input type="hidden" name="EmpID" />
<div class="panel panel-heading panel-primary">
<div class="panel-heading"><h3> Personal Information </h3></div>
<label> First Name </label>
<input name="Fname" class="form-control" ng-model="EmployeeInfo.Fname" required />
<small ng-show="EmployeeBasic.Fname.$touched && EmployeeBasicEmployeeBasic.Fname.$invalid">First Name is mandatory</small><br />
..........
MVC Controller:
[HttpPost]
public JsonResult AddEmployee(EmployeeInfo para)
{
return Json(new {success="success" },JsonRequestBehavior.AllowGet);
}
EmployeeInfo class:
public class EmployeeInfo
{
public string EmpID { get; set; }
public string Fname { get; set; }
public string Sname { get; set; }
public DateTime DOB { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public string Gender { get; set; }
public string UnitNo { get; set; }
public string StreetNo { get; set; }
public string Suburb { get; set; }
public string StateID { get; set; }
public string PostCode { get; set; }
Help is appreciated
this is because you are not posting the data through service,that's why you got null in backend
your post request should be like
$scope.EmployeeInfo ={'Fname':'',EmpID:''....all your child obj of EmployeeInfo }
$scope.submitBasicInfo = function (EmployeeInfo) {
$http({
method: 'POST',
url: '/EmployeeInfo/AddEmployee',
data: EmployeeInfo, // what data you want to send
headers: {'Content-Type': 'application/json'}
});
}
you can pass EmployeeInfo object from view
<form ng-submit="submitBasicInfo(EmployeeInfo)" name="EmployeeBasic" ng-controller="EmployeeBasicCtrl">

How to dynamically add more input boxes on button click?

I'm trying to build a pretty simple checklist app. I just can't quite get this right. When the user wants to add an item, he should click the button to add an item. Then there should be input boxes for item name and quantity. This part works but if the user then clicks the button to add another item, it should give him more input boxes, and this is what I can't get to work. Using Angular and typescript, not using $scope.
Here's my controller:
export class CreateItemListController {
public itemList;
public item;
public items = [];
public addNew() {
debugger;
this.items = []
var item = {itemName: "default name", itemQty: "default qty"}; // you can set default values here
this.items.push(item);
}
HTML
<form>
<div>
Title <input ng-model="controller.itemList.title" />
<div ng-repeat="item in controller.items">
Item Name <input ng-model="controller.item.itemName" />
Quantity <input ng-model="controller.item.itemQty" />
</div>
<button ng-click="controller.addNew()">Add New Item</button>
</div>
<button ng-click="controller.save()" type="submit">Submit</button>
</form>
and models
namespace BringIt.Models {
public class ItemList {
public int Id { get; set; }
public string Title { get; set; }
public DateTime EventDate { get; set; }
public ICollection<Item> Items { get; set; }
}
}
namespace BringIt.Models {
public class Item {
public int Id { get; set; }
public string ItemName { get; set; }
public int ItemQty { get; set; }
public string Person { get; set; }
public ItemList ItemList { get; set; }
}
}
I think, the problem is that you are again initializing your array in the addNew() function.
Change the function to
public addNew() {
var item = {itemName: "default name", itemQty: "default qty"};
this.items.push(item);
}
Notice I have removed the this.items = [] line

Resources