How to dynamically add more input boxes on button click? - angularjs

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

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

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

How to display Image from folder using ASP.NET MVC

I create entity outside my Project
this is solution Explorer
My entity Post
[Table("Post")]
public partial class Post
{
public int PostID { get; set; }
[Required]
[StringLength(256)]
public string Title { get; set; }
[StringLength(256)]
public string Description { get; set; }
[StringLength(256)]
public string Picture { get; set; }
public int CategoryID { get; set; }
[StringLength(10)]
public string ViewNumber { get; set; }
public int UserID { get; set; }
public DateTime CreateDate { get; set; }
public int LikeNumber { get; set; }
public int? CommentID { get; set; }
}
My Post Controller
[HttpPost]
public ActionResult UpPost(Post model, HttpPostedFileBase txtImg)
{
var db = new ShareImageDbContext();
if (ModelState.IsValid)
{
if (txtImg != null)
{
txtImg.SaveAs(HttpContext.Server.MapPath("~/Images/")
+ txtImg.FileName);
var post = new Post();
post.PostID = model.PostID;
post.Title = model.Title;
post.Description = model.Description;
post.CategoryID = model.CategoryID;
var userSession = new UserLogin();
userSession = (UserLogin)Session[ShareImage.Common.CommonConstants.USER_SESSION];
post.UserID = userSession.UserID;
post.CreateDate = DateTime.Now;
post.Picture = txtImg.FileName;
db.Posts.Add(post);
db.SaveChanges();
return RedirectToAction("Index", "Homeuser");
}
else
{
ModelState.AddModelError("", "Đăng ảnh thất bại!");
}
}
return View(txtImg);
}
My Post Database
I inserted some post
I want to display all Post on View. And I call Model as below.
#model IEnumerable<Model.EF.Post>
and I call foreach
#foreach (var item in Model)
but it has an error:
Object reference not set to an instance of an object.
I can display my image in Images folder as code following, but I want to show more attribute of Post table such as Title, Discription, CreateDate...
#foreach(var imgPath in Directory.GetFiles(Server.MapPath("~/Images")))
{
var img = new FileInfo(imgPath);
<img src="#Url.Content(String.Format("~/Images/{0}", img.Name))" />
<hr />
}
Please guide me how to fix it, Thanks!
In your view use String.IsNullOrWhiteSpace for strings and
<img src="<%= ResolveUrl(item.Picture) %>" alt="" /> for images
Problem caused because somewhere you do not set or create object. You have reference that has null value. It raises in view or controller. It will be nice if you provide your error message.

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

Angular + bind to navigation property

my server side code
public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
}
public class Employee
{
public int EmployeeId { get; set; }
public string EmployeePhoto { get; set; }
public virtual Person Person { get; set; }
[ForeignKey("Person")]
public virtual int PersonId { get; set; } // relates Employee to Person
}
I use breeze for dataservice on the clinet
var employee = manager.createEntity('Employee');
var person = manager.createEntity('Person');
employee.person = person;
the I bind to my viewModel (angular controller property like this)
vm.employee = employee
and I try to access in html like this
<input ng-model="vm.employee.person.firstName" placeholder="First Name" id="firstName" />
but it doesnt workout...
Help Plz

Resources