Angularjs Model passing null to MVC controller - angularjs

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">

Related

Data received from angularjs to MVC controller is null

Dears, I have two classes Master and detail named by Raterequest and Raterequestdetails. I have created a viewmodel contains both of them.
in Angularjs i have an object contains rate and a list contains orderdetails.
when i debug the controller the data received is null for both
here is the code
Rate request class
public class RateRequests
{
public int RateRequestsID { get; set; }
public DateTime RateRequestsDate { get; set; }
public string RateRequestName { get; set; }
public string RateRequestType { get; set; }
public string RateRequestMode { get; set; }
}
Rate request details class
public class RateRequestsLines
{
public int RateRequestsLinesID { get; set; }
public int RateRequestsID { get; set; }
[ForeignKey("RateRequestsID")]
public virtual RateRequests RateRequestsFK { get; set; }
public short FCLCNTRS { get; set; }
public short FCLCNTRSSIZE { get; set; }
public string FCLCNTRSTYPE { get; set; }
}
Rate request view model
public class RateRequestViewModel
{
public RateRequests rate { get; set; }
public IEnumerable<RateRequestsLines> ratelines { get; set; }
}
Angularjs
var linkers = angular.module("linkers", [])
.service("linkersSrv", function ($http) {
var urlBase = "/LinkersEgypt/";
this.save = function (url, ratee) {
return $http({
method: "POST",
url: urlBase + "/" + url,
data: ratee,
̶a̶s̶y̶n̶c̶:̶ ̶f̶a̶l̶s̶e̶,̶
})
};
})
.controller("linkersCon", function ($scope, linkersSrv) {
$scope.fcl = [];
$scope.addFCL = function () {
$scope.fcl.push({ FCLCNTRS: $scope.ncntrs, FCLCNTRSSIZE: $scope.csize, FCLCNTRSTYPE: $scope.ctype });
console.log($scope.fcl);
}
$scope.save = function () {
var ratee = {
rate: {
RateRequestsDate: $scope.rdate,
RateRequestName: $scope.rname,
RateRequestType: $scope.rtype,
RateRequestMode: $scope.smode
},
RateRequestsLines: $scope.fcl
};
console.log(ratee);
var promisepost = linkersSrv.save("RateRequest/AddAllRate", ratee);
promisepost.then(function () {
toastr.success("Successfully saved");
})
}
})
Rate controller
[HttpPost]
public JsonResult AddAllRate (RateRequestViewModel rate)
{
return new JsonResult();
}
Any help
Thanks in advance

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

Getting null values in action with List parameter

Im passing array data from angularjs to mvc controller
This is my angularjs code
$http({
url: '/Login/InsertDetails',
method: 'POST',
data: JSON.stringify(Data),
headers: { 'content-type': 'application/json' }
})
Json Data is
$scope.details = [{
name: "ammin",
age: "16",
city: "NY",
add: "true",
sal: 100
}, {
name: "joe",
age: "80",
city: "CH",
add: false,
sal: 200
}];
var Data = {
one: $scope.details
}
And in my controller i have method Insert with list parameter
public JsonResult Insert(List<Personel> P)
{
}
View Model class is like this
public class Personel
{
public string name { get; set; }
public int age { get; set; }
public string city { get; set; }
public string add { get; set; }
public string sal { get; set; }
}
But im getting null values in action method when i post the data from angularjs. what type of parameter should i use in action method

cascading dropdown in angular with key relation between them

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; }

I just want to pass the list to the asp.net web api using angularjs

I'm working on EAV database pattern.
My model is like this:
public class LeadsModel
{
public int? CompId { get; set; }
public int LeadID { get; set; }
public string LeadName { get; set; }
public string source { get; set; }
public string status { get; set; }
public int UserId { get; set; }
[Required]
public List<AttributesModel> AList { get; set; }
}
My view is like this. In view I'm fetching the list of attributes and I want to post back the using angularjs.
<div class="form-group" ng-repeat="At in Attributes" >
<label for="{{At.Attri}}" class="col-md-4 control-label">{{At.Attri}}</label>
<div class="col-md-8">
#*<input type="hidden" name="{{At.AID}}" data-ng-model="newLead.NewAlist" />*#
<input type="text" class="form-control" id="{{At.Attri}}" name="{{At.Attri}}" pl placeholder="Enter {{At.Attri}}" data-ng-model="newLead.AList.AttriValue" ng-blur="AddItemToList(newLead.Alist.AttriValue)" />
</div>
</div>
My Angular code is like this
$scope.add = function ()
{
$scope.loading = true;
this.newLead.AList = $scope.listt;
$http.post('/api/Leads/Posttbl_Lead', this.newLead).success(function (data) {
alert("Added Successfully!!");
$scope.loading = false;
$scope.addLMode = false;
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
$scope.loading = false;
});
}
and my web api controller is like this
public IHttpActionResult Posttbl_Lead(LeadsModel tbl_Lead)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
tbl_Lead newLead = new tbl_Lead();
newLead.LeadName = tbl_Lead.LeadName;
newLead.source = tbl_Lead.source;
newLead.status = tbl_Lead.status;
newLead.LeadName = tbl_Lead.LeadName;
newLead.CompId = tbl_Lead.CompId;
db.tbl_Lead.Add(newLead);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = tbl_Lead.LeadID }, tbl_Lead);
}
Use this code to post your newLead of AngularJs to tbl_Lead of your API contoller. This is the complementary link for You to pass the list/ array object to You API.
$http({
contentType: "application/json; charset=utf-8",//required
method: "POST",
url: '/api/Leads/Posttbl_Lead',
dataType: "json",//optional
data:{ "tbl_Lead": newLead },
async: "isAsync"//optional
})
.success( function (response) {
alert('Saved Successfully.');
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
$scope.loading = false;
});
Edit-1
Below mentioned is the way to send AList inside LeadsModel to your api.
LeadsModel to send onto the server via API.
{
CompId=compId,
LeadID=leadID,
AList=[{FirstObject=firstObject},{SecondObject=secondObject}]
}

Resources