POST dynamically added Lists to Controller as Json and redirect view - arrays

Description
I'm am creating a dynamic table where the user can select regions in a dropdown lists. On "add" the user can also add new table rows with region dropdown lists included. On POST, a list of Regions should be posted to the controller where it´s being saved to the SavingPlan model.
Problem
Ajax is returning null to my controller even though I have saved selected option-data to string arrays which is being posted to the controller.
Addition
I am fairly new to ASP.NET MVC so please have that in mind when commenting. I am open minded towards doing things differently but I´d very much appreciate I someone would be able to guid me and my code in the right direction.
Region Model
public class Region
{
public int Id { get; set; }
public string Name { get; set; }
}
Saving Plan Model
public SavingPlan()
{
}
public SavingPlan(List<Region> regionList)
{
RegionList = regionList;
}
public int Id { get; set; }
public ApplicationUser AssessmentUser { get; set; }
public IEnumerable<Region> RegionLookUp { get; set; }
public bool IsActive { get; set; }
public byte RegionId { get; set; }
public Region Region { get; set; }
public List<Region> RegionList { get; set; }
}
SavingPlan - ViewModel
public class SavingPlan
{
public SavingPlan()
{
}
public SavingPlan(List<Region> regionList)
{
RegionList = regionList;
}
public int Id { get; set; }
public ApplicationUser AssessmentUser { get; set; }
public IEnumerable<Region> RegionLookUp { get; set; }
public bool IsActive { get; set; }
public byte RegionId { get; set; }
public Region Region { get; set; }
public List<Region> RegionList { get; set; }
}
Controller Action GET - NewSavingPlan
public ActionResult NewSavingPlan()
{
SavingPlanAssessmentView viewModel = new SavingPlanAssessmentView();
viewModel.SavingPlan = new SavingPlan();
var regions = _context.Regions
.ToList();
viewModel.RegionLookUp = regions;
return View(viewModel);
}
Controller Action POST - Save SavingPlan
[HttpPost]
public JsonResult SaveList(string RegionList)
{
var urlBuilder = new UrlHelper(Request.RequestContext);
var url = urlBuilder.Action("Index", "Assessments");
string[] arr = RegionList.Split(',');
foreach (var item in arr)
{
var region = item;
}
return Json(new { status = "success", redirectUrl = Url.Action("Index","Home") });
}
SavingPlan Partial View
#model BBRG.ViewModels.SavingPlanAssessmentView
<h2>#Model.Heading</h2>
#*#using (Html.BeginForm("Save", "Assessments", FormMethod.Post))
{*#
#*#Html.AntiForgeryToken()
#Html.HiddenFor(m => m.Id)*#
<legend>Saving Plan</legend>
<table id="regionTable" class="table table-striped">
<thead>
<tr>
<td>Region</td>
<td> <button id="add" type="button" class="btn btn-link">Add</button></td>
<td></td>
</tr>
</thead>
<tbody>
<tr id="regionRow_1">
<td>
#Html.DropDownListFor(m => m.RegionId, new SelectList(Model.RegionLookUp, "Id", "Name"), "Select Region", new { #class = "form-control Region", id = "Region_1", type="string", name = "Region", selected="false" })
</td>
<td>
<button data-region-id="#Model.RegionId" id="deleteRegion" type="button" class="btn btnDeleteRegion btn-link btn-xs btn" btn-xs>remove</button>
</td>
</tr>
</tbody>
</table>
<hr />
<p>
#Html.HiddenFor(m => m.Id)
<button data-saving-id="#User.Identity" onclick="saveRegion()" type="submit" calss="btn btn-default js-toggle-save">Save</button>
</p>
Jquery - Add new table row with dropdownlist
$(document).ready(function () {
var counter = 2;
$(function () {
$('#add').click(function () {
$('<tr id="regionRow_' + counter + '">'
+ '<td>'
+ '<select type="text" value="RegionId" name="Region" id="Region_'+ counter+'" class="form-control Region" " >'
+ $(".Region").html()
+ '</select>'
+ '</td>'
+ '<td>'
+ '<button data-region-id= id="deleteRegion" type="button" class="btn btnDeleteRegion btn-link btn-xs btn" btn-xs>remove</button>'
+ '</td>'
+ '</tr>').appendTo('#regionTable');
counter++;
return false;
});
});
});
Jquery and .ajax for POST
{
<script src="~/Scripts/SavingPlanScripts.js"></script>
<script>
var saveRegion = (function () {
var array = [];
var commaSeperated = "";
var count = 1;
$("#regionTable tbody .Region").each(function (index, val) {
var regionId = $(val).attr("Id");
var arr = regionId.split('_');
var currentRegionId = arr[1];
var isSelected = $(".Region option").is(':selected', true);
if (isSelected) {
array.push(currentRegionId);
}
count++;
});
if (array.length != 0) {
commaSeperated = array.toString();
$.ajax({
type: "POST",
dataType: "json",
contentType: "/application/json",
url: "/SavingPlans/SaveList",
data: { "RegionList": commaSeperated },
success: function (json) {
if (json.status == "success") {
window.location.href = json.redirectUrl;
};
}
});
};
});
</script>
}```

I found the solution to my problem, I forgot to stringify my .ajax data. If anyone still want to provide me with some constructive input, please don´t hesitate.
$.ajax({
url: "../SavingPlans/SaveList",
data: JSON.stringify({ RegionId: commaSeperated }),
type: "POST",
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (json) {
if (json.status == "success") {
window.location.href = json.redirectUrl;
};
}
});

Related

Asp.net core database data displayed more often than existing

I'm wondering why my ASP.NET Core MVC Project is listing my data double.
What it should be:
What it gives me:
See the difference?
My Controller (Controller Class - Index()-Method):
[HttpGet()]
public async Task<IActionResult> Index(string id)
{
IQueryable<string> werkeQuery = from m in _context.TestDbSet
orderby m.Id
select m.Id;
var test = from t in _context.TestDbSet
orderby t.Id
select t;
if (!string.IsNullOrEmpty(id))
{
test = (IOrderedQueryable<TestSet>)_context.TestDbSet.Where(x => x.Id == id);
}
var filter = new TestSet
{
Werke = new SelectList(await werkeQuery.Distinct().ToListAsync()),
Liste = await test.ToListAsync()
};
return View(filter);
}
My Model-Class (could there be the error?):
`[Table("Test", Schema = "dbo")]
public class TestSet
{
[Key]
[Display(Name = "Werk")]
[Column("Id")]
public string Id { get; set; }
[Display(Name = "Mitarbeiter ID")]
[Column("M_ID")]
public string M_Id { get; set; }
[Column("Beginn")]
[DataType(DataType.Date)]
public DateTime Beginn { get; set; }
[Column("Ende")]
[DataType(DataType.Date)]
public DateTime Ende { get; set; }
[NotMapped]
public SelectList Werke { get; set; }
[NotMapped]
public List<TestSet> Liste { get; set; }
}`
My View (relevant code: displayed list):
`#model DienstplanAnzeige.Models.TestSet
#{
ViewData["Title"] = "Startseite";
}
<form asp-controller="Home" asp-action="Index" method="get">
<div class="input-group mb-3">
<select class="custom-select" asp-for="Id" asp-items="#Model.Werke">
<option value="" disabled selected>Werk auswählen</option>
</select>
<input type="submit" value="Anzeigen" class="btn btn-outline-secondary" />
</div>
</form>
<table class="table table-hover">
<thead>
<tr>
<th>#Html.DisplayNameFor(model => model.Liste[0].Id)</th>
<th>#Html.DisplayNameFor(model => model.Liste[0].M_Id)</th>
<th>#Html.DisplayNameFor(model => model.Liste[0].Beginn)</th>
<th>#Html.DisplayNameFor(model => model.Liste[0].Ende)</th>
</tr>
</thead>
<tbody>
#foreach(var item in Model.Liste)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.Id)</td>
<td>#Html.DisplayFor(modelItem => item.M_Id)</td>
<td>#Html.DisplayFor(modelItem => item.Beginn)</td>
<td>#Html.DisplayFor(modelItem => item.Ende)</td>
</tr>
}
</tbody>
</table>`
My Context-Class (named "TestContext"):
public class TestContext : DbContext
{
public TestContext(DbContextOptions<TestContext> options)
: base(options)
{
}
public DbSet<TestSet> TestDbSet { get; set; }
}
Can someone help me?
In your controller, since your id property and parameter is in string therefore instead of using == comparison operator you should use Equals(...) method of string class i.e.
if (!string.IsNullOrEmpty(id))
{
test = (IOrderedQueryable<TestSet>)_context.TestDbSet.Where(x => x.Id.Equals(id, StringComparison.InvariantCultureIgnoreCase);
}

"There is no ViewData item of type 'IEnumerable' that has the key" Problem

I need to set "ManagerID" as the "id" from "Employee".(I mean ManagerID and id are linked). I write codes but have a problem. It shows items with dropdownlist correctly but when I try to apply, it says "There is no ViewData item of type 'IEnumerable' that has the key ManagerID"
View
<div class="form-group">
#Html.LabelFor(model => model.ManagerID, "ManagerID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ManagerID, (List<SelectListItem>)ViewBag.Manager , htmlAttributes: new { #class = "control-label col-md-2" })
#Html.ValidationMessageFor(model => model.ManagerID, "", new { #class = "text-danger" })
</div>
</div>
Controller
public ActionResult Add_Department()
{
List<SelectListItem> employeeList = (from a in db.Employee.ToList()
select new SelectListItem
{
Text = a.Name + a.Surname,
Value = a.id.ToString()
}).ToList();
ViewBag.Manager = employeeList;
return View();
}
[HttpPost]
public ActionResult Add_Department(Department_Info department)
{
if (ModelState.IsValid)
{
db.Department_Info.Add(department);
db.SaveChanges();
return RedirectToAction("Main");
}
return View(department);
}
Model:
public partial class Department_Info
{
public int id { get; set; }
public string Department { get; set; }
public Nullable<int> ManID { get; set; }
}
The problem is you are not saving your Manager dropdown to ViewBag in your post action because if your request is not validated successfully then you will be returned the same page but at this time you ViewBag.Manager is null so it will cause an error.
So you need to add ViewBag.Manager SelectList also in the post action method.
[HttpPost]
public ActionResult Add_Department(Department_Info department)
{
if (ModelState.IsValid)
{
db.Department_Info.Add(department);
db.SaveChanges();
return RedirectToAction("Main");
}
List<SelectListItem> employeeList = (from a in db.Employee.ToList()
select new SelectListItem
{
Text = a.Name + a.Surname,
Value = a.id.ToString()
}).ToList();
ViewBag.Manager = employeeList;
return View(department);
}
I've also noticed that your Manager dropdown name is ManagerID while your Department_Info model doesn't have the field with the same name. Actually, this is the problem which produces the worst condition and your first problem encounters.
You need to update your Department_Info model:
public partial class Department_Info
{
public int id { get; set; }
public string Department { get; set; }
public Nullable<int> ManagerID { get; set; }
}
Or you need to change your dropdown name:
#Html.DropDownList("ManagerID", (List<SelectListItem>)ViewBag.Manager, htmlAttributes: new { #class = "control-label col-md-2" })
Hopefully, It will resolved your problem.

How to get the values of the child element from the parent element in angularjs

I have two database tables with one being the parent and the other being the child. The parent table has a reference to the child table. Database table was generated using code-first approach with the data models are below:
[Table("Family")]
public partial class Family
{
public int Id { get; set; }
public string Surname { get; set; }
public string FirstName { get; set; }
public int RoleId { get; set; }
public int FuId { get; set; }
public int RiskAreaId { get; set; }
public int LocationId { get; set; }
public DateTime CreatedDate { get; set; }
[ForeignKey("RoleId")]
public virtual Role Role { get; set; }
[ForeignKey("FuId")]
public virtual FamilyUnit FamilyUnit { get; set; }
[ForeignKey("RiskAreaId")]
public virtual RiskArea RiskArea { get; set; }
[ForeignKey("LocationId")]
public virtual Location Location { get; set; }
}
And the FamilyUnit table i below:
[Table("FamilyUnit")]
public partial class FamilyUnit
{
public int Id { get; set; }
[Column(TypeName = "varchar")]
[StringLength(50)]
[Required]
public string FamilyUnitName { get; set; }
public virtual IEnumerable<Family> Families { get; set; }
}
I then created a webAPI project so my project can consume the APIs. My Api is shown below:
[EnableCors("*", "*", "*")]
public class FamilyUnitController : ApiController
{
FamilyUnitBs familyUnitObjBs;
public FamilyUnitController()
{
familyUnitObjBs = new FamilyUnitBs();
}
[ResponseType(typeof(IEnumerable<FamilyUnit>))]
public IHttpActionResult Get()
{
var famUnits = familyUnitObjBs.GetALL();
return Ok(famUnits);
}
[ResponseType(typeof(FamilyUnit))]
public IHttpActionResult Get(int id)
{
FamilyUnit familyUnit = familyUnitObjBs.GetByID(id);
if (familyUnit != null)
return Ok(familyUnit);
else
return NotFound();
}
[ResponseType(typeof(FamilyUnit))]
public IHttpActionResult Delete(int id)
{
FamilyUnit familyUnit = familyUnitObjBs.GetByID(id);
if (familyUnit != null)
{
familyUnitObjBs.Delete(id);
return Ok(familyUnit);
}
else
{
return NotFound();
}
}
}
I then created another project called for the front-end of the application to consume the API methods.
Below is the angularjs controller with the factory service
appEIS.factory('familyMgmtService', function ($http,$rootScope) {
famMgmtObj = {};
famMgmtObj.getAll = function () {
var Fams;
Fams = $http({ method: 'Get', url:$rootScope.ServiceUrl+ 'FamilyUnit' }).
then(function (response) {
return response.data;
});
return Fams;
};
famMgmtObj.createFamily = function (fam) {
var Fam;
Fam = $http({ method: 'Post', url:$rootScope.ServiceUrl+ 'Family', data: fam }).
then(function (response) {
return response.data;
}, function(error) {
return error.data;
});
return Fam;
};
famMgmtObj.deleteFamilyById = function (eid) {
var Fams;
Fams = $http({ method: 'Delete', url:$rootScope.ServiceUrl+ 'FamilyUnit', params: { id: eid } }).
then(function (response) {
return response.data;
});
return Fams;
};
famMgmtObj.getFamilyByFuId = function (fid) {
var Fams;
console.log(fid);
Fams = $http({ method: 'Get', url: $rootScope.ServiceUrl + 'Family', params: { id: fid } }).
then(function (response) {
return response.data;
});
return Fams;
};
return famMgmtObj;
});
appEIS.controller('familyMgmtController', function ($scope, familyMgmtService, utilityService, $window) {
$scope.Sort = function (col) {
$scope.key = col;
$scope.AscOrDesc = !$scope.AscOrDesc;
};
familyMgmtService.getAll().then(function (result) {
$scope.Fams = result;
console.log(result);
});
$scope.CreateFamily = function (Fam, IsValid) {
if (IsValid) {
$scope.Fam.Password = utilityService.randomPassword();
familyMgmtService.createFamily(Fam).then(function (result) {
if (result.ModelState == null) {
$scope.Msg = " You have successfully created " + result.FamilyId;
$scope.Flg = true;
utilityService.myAlert();
$scope.serverErrorMsgs = "";
familyMgmtService.getAll().then(function (result) {
$scope.Fams = result;
});
}
else {
$scope.serverErrorMsgs = result.ModelState;
}
});
}
};
$scope.DeleteFamilyById = function (Fam) {
if ($window.confirm("Do you want to delete Family with Id:" + Fam.FamilyId + "?")) {
familyMgmtService.deleteFamilyById(Fam.FamilyId).then(function (result) {
if (result.ModelState == null) {
$scope.Msg = " You have successfully deleted " + result.FamilyId;
$scope.Flg = true;
utilityService.myAlert();
familyMgmtService.getAll().then(function (result) {
$scope.Fams = result;
});
}
else {
$scope.serverErrorMsgs = result.ModelState;
}
});
}
};
$scope.GetFamilyByFuId = function (Fam) {
familyMgmtService.getFamilyByFuId(Fam.fid).then(function (result) {
console.log(result);
$scope.Fams = result;
});
};
$scope.CreateMultiFamily = function () {
var file = $scope.myFile;
var uploadUrl = "http://localhost:60736/api/Upload/";
utilityService.uploadFile(file, uploadUrl, $scope.eid).then(function (result) {
$scope.image = result;
});
};
});
The family unit is displaying well in an accordion list but the various families are not getting displayed using the familyUnit Id as shown below:
<div class="panel-body">
<div dir-paginate="emp in Fams | filter:search | orderBy:key:AscOrDesc | itemsPerPage:10" class="wrapper center-block">
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="heading{{emp.Id}}">
<h4 class="panel-title">
<div role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse{{emp.Id}}" aria-expanded="true" aria-controls="collapse{{emp.Id}}">
{{emp.FamilyUnitName}}
</div>
</h4>
</div>
<div id="collapse{{emp.Id}}" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="heading{{emp.Id}}">
<div class="panel-body">
<div ng-repeat="f in emp.Families">{{f.FirstName}} - {{f.Surname}}</div>
</div>
</div>
</div>
</div>
</div>
Based on the discussion in the comments, this issue looks like the issue with data and not with the front-end (yet).
You need to load the Families details while getting the FamilyUnit in your Get(int id) method. There are two ways through which you can do the early loading.
Use Include with Linq, like:
var familyUnit = familyUnitObjBs.FamilyUnits
.Include(fu => fu.Families)
.Where (fu +. fu.Id == Id)
.ToList();
The second option could be using the early loading by removing the virtual from your data structure, which might be an issue if you plan to add more methods or maybe if you have test cases to override, still, it will look like:
[Table("FamilyUnit")]
public partial class FamilyUnit
{
public int Id { get; set; }
[Column(TypeName = "varchar")]
[StringLength(50)]
[Required]
public string FamilyUnitName { get; set; }
public IEnumerable<Family> Families { get; set; }
}
You can find more details about lazy loading and early loading at:
https://msdn.microsoft.com/en-us/library/jj574232(v=vs.113).aspx
EDIT:
1. You can use strong type instead of var for familyUnit:
List<FamilityUnit> familyUnit= familyUnitObjBs.FamilyUnits
.Include(fu => fu.Families)
.Where (fu +. fu.Id == Id)
.ToList();
Get the list instead of FirstOrDefault() if you need whole list:
return db.Familiies.Where(x => x.FuID == id).ToList();

How to display/store and retrieve image as varbinary(MAX) using ASP.NET MVC view

I am new to ASP.NET MVC, so kindly excuse for mistakes.
I need a view page (index.cshtml) where I can display the image, change/delete the image by storing it in Varbinary(max) column in a SQL Server table.
There are these columns in the database table:
ID int primary key Identity not null,
ImageName nvarchar(50) ,
ImagePicInBytes varbinary(MAX) null
I am using a Image.cs with this code:
public class Image
{
public int ID {get; set;}
public string ImageName {get; set;}
public byte[] ImagePicInBytes {get; set;}
}
ImageContext class as below
public class ImageContext : DbContext
{
public DbSet<Image> Images { get; set; }
}
Connection string as below
<connectionStrings>
<add name="ImageContext"
connectionString="server=.; database=Sample; integrated security =SSPI"
providerName="System.Data.SqlClient"/>
</connectionStrings>
ImageController as below
public class ImageController : Controller
{
private ImageContext db = new ImageContext();
// GET: /Image/
public ActionResult Index()
{
return View(db.Images.ToList());
}
// GET: /Image/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Image image = db.Images.Find(id);
if (image == null)
{
return HttpNotFound();
}
return View(image);
}
}
Have created views as below
public class ImageController : Controller
{
private ImageContext db = new ImageContext();
// GET: /Image/
public ActionResult Index()
{
return View(db.Images.ToList());
}
// GET: /Image/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Image image = db.Images.Find(id);
if (image == null)
{
return HttpNotFound();
}
return View(image);
}
// GET: /Image/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Image image = db.Images.Find(id);
if (image == null)
{
return HttpNotFound();
}
return View(image);
}
// POST: /Image/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Image image = db.Images.Find(id);
db.Images.Remove(image);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
My create.cshtml (view) as below
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.ImageName)
</th>
<th>
#Html.DisplayNameFor(model => model.ImagePicInBytes)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.ImageName)
</td>
<td>
#Html.DisplayFor(modelItem => item.ImagePicInBytes)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
#Html.ActionLink("Details", "Details", new { id=item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
I have the below 3 questions
How can I create a new record in datatable by uploading new image from file system to Varbinary column in database?
How can I have the view to have FILEUPLOAD control in the 'create View' and 'Edit view'
Can I use HttpPostedFileBase to achieve the above from Create.cshtml? If yes: how? Any suggestions or reference links available?
first of all create a viewmodel for Image class
public class ImageViewModel
{
public string ImageName {get; set;}
public HttpPostedFileBase ImagePic {get; set;}
}
then for uploading a photo in your create view
#model ExmpleProject.Models.ImageViewModel
#using (Html.BeginForm("Create", "ControllerName", FormMethod.Post, new {enctype="multipart/form-data"})){
#Html.AntiForgeryToken()
#Html.LabelFor(m => m.ImageName)
#Html.TextBoxFor(m => m.ImageName)
#Html.LabelFor(m => m.ImagePic )
#Html.TextBoxFor(m => m.ImagePic , new { type = "file" })
<br />
<input type="submit" name="Submit" id="Submit" value="Upload" />
}
then in post method of your controller for create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ImageViewModel model)
{
if (ModelState.IsValid)
{
var uploadedFile = (model.ImagePic != null && model.ImagePic.ContentLength > 0) ? new byte[model.ImagePic.InputStream.Length] : null;
if (uploadedFile != null)
{
model.ImagePic.InputStream.Read(uploadedFile, 0, uploadedFile.Length);
}
Image image = new Image
{
ImageName = model.ImageName,
ImagePicInBytes = uploadedFile
}
db.Create(image);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
so for your edit method you can do similar implementation but instead of Create(image) use Update(image)

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