How to show use ng-repeat to show model values - c#

I can't figure out how to connect my model with my angular view in ASP.net MVC. I am trying to show the FirstName and LastName values from the User model.
Here is my view:
<table class="table" ng-app="UserApp" style="background: white;" height="1200">
<tbody ng-controller="SearchController">
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr ng-repeat="user in User">
<td></td>
<td>{{ user.FirstName }}</td>
<td>{{ user.LastName }}</td>
</tr>
}
</tbody>
Here is the controller:
public class SearchController : Controller
{
private GigDB db = new GigDB();
// GET: Search
public ActionResult Search()
{
List<User> users;
users = db.Users.ToList();
return View(users);
}
}
Here is the model:
public class User
{
[Key]
public int UserID { get; set; }
//[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
//[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
Lastly, the script:
var app = angular.module('UserApp', []);
app.controller('SearchController', function ($scope) {
$scope.model = #Html.Raw(Json.Encode(Model));
console.log($scope.model);
console.log($scope.model[0].FirstName);
});
What I am confused about, is the console.log in the script is working and shows the user objects correctly with all of the values. Also when I console.log #scope.model[0], that pulls the value correctly as well but in the angular view I cannot get the values to show at all.

Code C# like this to return Json object
public JsonResult Search()
{
List<User> users;
users = db.Users.ToList();
return JSon(users,JsonRequestBehavior.AllowGet);
}
and script should like this to call data:
app.controller('SearchController', function ($scope) {
$http({
method: 'GET',
url: '/SearchController/Search'
}).then(function successCallback(response) {
$scope.User= response.data;
});
});
It may help you

So, originally in my view I had:
<table class="table" ng-app="UserApp" style="background: white;" height="1200">
<tbody ng-controller="SearchController">
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr ng-repeat="user in model"> //model here instead of User..
<td></td>
<td>{{ user.FirstName }}</td>
<td>{{ user.LastName }}</td>
</tr>
}
and I thought that it was not working, but as it turns out the table just stretched far down on the screen and I couldn't see the values being shown. Oops.

Related

How to edit/update a database entity column with a button in ASP.NET MVC C#

I am stuck on a function I want to create and can't figure out how to implement it. I have a database table called "OrderDetails" and in the table I have a column called "StatusID". The StatusID has 3 possible values (1) which = "Pending" ,(2) which = "Shipped", and (3) which = "Completed. I have a partial view created on a main dashboard page that pulls up the OrderDetails table from database and only shows the orders that have a StatusID value of 1 or 2. I put two buttons on the table and what I'd like to accomplish is when the user clicks on button1, it would change the StatusID to 2 (which is "Shipped"). And if the user clicks on button2, it would change the StatusID to 3 (which is "Completed"). By change I mean, whatever record (or Order#) the button is on, it would edit/update that value in the database. I can't seem to get it to work from a button click, I've tried everything I can think of and no luck, but just as a disclaimer, I am very new to ASP.net MVC C# and web development in general so I'm definitely not an expert with extensive knowledge. Is what I'm trying to do possible with buttons?
Here is my model:
namespace AMS_ITAMSdb.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
using System.Web;
using System.Web.Mvc;
public partial class OrderDetail
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage",
"CA2214:DoNotCallOverridableMethodsInConstructors")]
public OrderDetail()
{
this.ProductOrders = new HashSet<ProductOrder>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Display(Name = "Order ID")]
public int OrderID { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> Order_Date { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Date Needed")]
public Nullable<System.DateTime> Date_Requested { get; set; }
[Display(Name = "Order Status")]
public Nullable<int> StatusID { get; set; }
public virtual OrderStatu OrderStatu { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ProductOrder> ProductOrders { get; set; }
}
}
Here is my controller:
namespace AMS_ITAMSdb.Controllers
{
public class DashboardsController : Controller
{
private ItamsEntities db = new ItamsEntities();
public ActionResult Index()
{
return View();
}
public ActionResult Admin()
{
return View();
}
//GET: OpenOrders
public ActionResult OpenOrders(OrderDetail orderDetail)
{
var orderDetails = db.OrderDetails.Where(o => o.StatusID < 3).ToList();
return PartialView("OpenOrders", orderDetails);
}
}
}
and Here is my view page:
#model IEnumerable<AMS_ITAMSdb.Models.OrderDetail>
#{
Layout = null;
}
<div class="container">
<table class="table">
<tr class="table-hdr">
<th class="open-lbl">
Open
</th>
<th class="ord-lbl">
Order #
</th>
<th class="orderDate-lbl">
Order Date
</th>
<th class="products-lbl">
Products
</th>
<th class="dateNeeded-lbl">
Date Needed
</th>
<th class="status-lbl">
Status
</th>
<th>
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td class="open-ctl">
<u>Open</u>
</td>
<td class="ord-ctl">
#Html.DisplayFor(modelItem => item.OrderID)
</td>
<td class="orderDate-ctl">
#Html.DisplayFor(modelItem => item.Order_Date)
</td>
<td class="products-ctl">
<a>#Html.ActionLink("View", "ProductOrder", "Dashboards", new { id = item.OrderID })</a>
</td>
<td class="dateNeeded-ctl">
#Html.DisplayFor(modelItem => item.Date_Requested)
</td>
<td class="status-ctl">
#Html.DisplayFor(modelItem => item.OrderStatu.Status)
</td>
<td>
<button class="button" type="submit"><span class="fa-solid fa-truck-fast"></span></button>
<button class="button" type="submit"><span class="fa-solid fa-clipboard-check"></span></button>
<button class="button"><span class="fa-solid fa-print"></span> Print</button>
</td>
</tr>
}
</table>
</div>
I have tried doing a function in the controller called "ToShipped" and "ToCompleted" where I called up from the button when it is clicked but it didn't work. This is the code I tried:
//POST: Dashboards/ToShipped
[HttpPost]
public ActionResult ToShipped(OrderDetail orderDetail)
{
if (ModelState.IsValid)
{
orderDetail.StatusID = 2;
db.Entry(orderDetail).State = EntityState.Modified;
db.SaveChanges();
}
var orderDetails = db.OrderDetails.Include(o => o.Department).Include(o => o.OrderStatu).Where(o => o.StatusID < 3).ToList();
return PartialView("OpenOrders", orderDetails);
}
//POST: Dashboards/ToCompleted
[HttpPost]
public ActionResult ToCompleted(OrderDetail orderDetail)
{
if (ModelState.IsValid)
{
orderDetail.StatusID = 3;
db.Entry(orderDetail).State = EntityState.Modified;
db.SaveChanges();
}
var orderDetails = db.OrderDetails.Where(o => o.StatusID < 3).ToList();
return PartialView("OpenOrders", orderDetails);
}
And then in my view on the input button, I tried calling the function by doing a Url.Action:
<input class ="button" type="submit" formaction="#Url.Action("ToShipped", "Dashboards")" formmethod="post" />
I don't know where I'm going wrong, any help or suggestions, would be greatly appreciated!!!

Razor Pages AJAX - filling the model after AJAX delete call

I'm new to AJAX and trying to delete a row in the table without refreshing the whole page. When the button gets clicked the row is succesfully deleted from database, but i get this error:
NullReferenceException: Object reference not set to an instance of an
object.
Meaning the Model is empty. I don't understand how should I fill the model again after AJAX call.
Anybody dealt with this before?
My model class:
public class Person
{
public int PersonId { get; set; }
public string PersonName { get; set; }
public string PersonAddress { get; set; }
}
My Index.cshtml.cs:
[ValidateAntiForgeryToken]
public class IndexModel : PageModel
{
private readonly WebApplication20.Data.ApplicationDbContext _context;
public IndexModel(WebApplication20.Data.ApplicationDbContext context)
{
_context = context;
}
public IList<Models.Person> Person { get;set; }
public async Task OnGetAsync()
{
Person = await _context.Person.ToListAsync();
}
public IActionResult OnPostDeleteById(int id)
{
var pers = _context.Person.Find(id);
_context.Remove(pers);
_context.SaveChanges();
Person = _context.Person.ToList();
return new JsonResult
("Customer Deleted Successfully!");
}
}
My Index.cshtml:
#page
#model WebApplication20.Pages.Person.IndexModel
<p>
<a asp-page="Create">Create New</a>
</p>
<div id="msg"></div>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Person[0].PersonName)
</th>
<th>
#Html.DisplayNameFor(model => model.Person[0].PersonAddress)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Person)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.PersonName)
</td>
<td>
#Html.DisplayFor(modelItem => item.PersonAddress)
</td>
<td>
<form method="post">
<button class="btn btn-danger" onclick="DeleteId('#item.PersonId');">Delete</button>
</form>
</td>
</tr>
}
</tbody>
</table>
Javascript (embed in script tag at bottom of page)
<script>
function DeleteId(id) {
var options = {};
options.url = "/Person/Index?handler=DeleteById&id=" + id;
options.beforeSend = function(xhr) {
xhr.setRequestHeader("MY-XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
};
options.dataType = "json";
options.type = "POST";
options.success = function (data) {
$("#msg").html("Great Success");
};
options.error = function () {
$("#msg").html("Error something went wrong");
};
$.ajax(options);
}
</script>

Cannot get the Id through the API in the component(Angular, .net core)

I'm developing a test project for learning Angular. My problem - the student's id from the service is equal to null. I have a controller - StudentController to work with data. Here is a snippet of code where I get data on students:
// GET: api/students
[HttpGet]
public IActionResult GetAll()
{
var students = _unitOfWork.Students.GetAll();
return Ok(students);
}
And here is my domain model(Student.cs) with UnitOfWork method - GetAll():
public class Student
{
public int StudentId{get;set;}
public string Name { get; set; }
public DateTime bDate {get;set;}
}
GetAll(Repository.cs):
public virtual IEnumerable<TEntity> GetAll()
{
return _entities.ToList();
}
Next,I created a service for getting data from the API(student.service.ts):
private readonly _StudentsUrl: string = "/api/students";
GetAll()
{
return this.http.get(this._StudentsUrl)
.map(res => res.json());
}
So, in the client part student's id is undefined.
(students.component.ts)
export class StudentsComponent {
students:Student[];
constructor(private studentService: StudentService) { }
ngOnInit() {
this.studentService.GetAll()
.subscribe(students => this.students = students);
}
}
export class Student {
StudentId: number;
Name: string;
bDate:DateTimeFormat
}
In student.component.html i get students data, name and bDate properly, but StudentId is not.
<tr *ngFor="let st of students">
<td>{{ st.StudentId }}</td>
<td>{{ st.name }}</td>
<td>{{ st.bDate }}</td>
<td>
<a [routerLink]="['/students/', st.StudentId]">View</a>
</td>
</tr>
I tested my StudentController with Postman and everything is passed correctly.
What am i doing wrong?
This is strange, but I found a solution by writing instead of StudentId on studentId. Now it works perfectly. So in html i change from:
<td>{{ st.StudentId }}</td>
to:
<td>{{ st.studentId }}</td>
Modified code:
<tr *ngFor="let st of students">
<td>{{ st.studentId }}</td>
<td>{{ st.name }}</td>
<td>{{ st.bDate }}</td>
<td>
<a [routerLink]="['/students/', st.studentId]">View</a>
</td>
</tr>

ASP.NET MVC CRUD with LocalDb savechanges error

I'm using VS 2015 and I created an ASP.NET MVC project and added a couple things (log in and register did work fine with Localdb called MyDatabase.mdf) that did work.
CRUD only create function in db the rest will come later.
But now I can't get this work. Inside the LocalDb called MyDatabase.mdf, I have created another table called Amsterdam:
[MyDatabase.mdf][1]
And this is my MainDbContext.cs - here I added
public DbSet<Amsterdam> Amsterdam { get; set; }
And in my Home folder I wrote Amsterdam.cshtml like this:
#model IEnumerable<MyFirstWebsite.Models.Amsterdam>
#{
ViewBag.Title = "Amsterdam";
var username = User.Identity.Name;
}
<h2>#username's Bestellijst Amsterdam</h2>
#using (Html.BeginForm())
{
<span>Enter new item: </span>
<br/>
<input type="text" name="new_item"/>
<br/>
<span>Public post?</span>
<input type="checkbox" name="check_public"/><br/>
<br/>
<input type="submit" value="Add Item"/>
}
<br/>
<table class="table table-bordered table-condensed">
<thead>
<tr>
<th style="text-align: center;">Id Bestelling</th>
<th style="text-align: center;">Details Bestelling</th>
<th style="text-align: center;">Time - Ontvangen Bestelling</th>
<th style="text-align: center;">Time - Verzonden Bestelling</th>
<th style="text-align: center;">Edit</th>
<th style="text-align: center;">Delete</th>
<th style="text-align: center;">Public Post</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;"></td>
<td style="text-align: center;"></td>
<td style="text-align: center;"></td>
<td style="text-align: center;"></td>
<td style="text-align: center;">
Edit
</td>
<td style="text-align: center;">
Edit
</td>
<td style="text-align: center;"></td>
</tr>
</tbody>
</table>
And in my Models folder I created Amsterdam.cs which looks like this:
namespace MyFirstWebsite.Models
{
public class Amsterdam
{
[Key]
public int Id { get; set; }
public string Details { get; set; }
public string Date_Posted { get; set; }
public string Time_Posted { get; set; }
public string Date_Edited { get; set; }
public string Time_Edited { get; set; }
public string Public { get; set; }
public int User_Id { get; set; }
}
}
And in my Controllers folder my HomeController looks like this:
public ActionResult Amsterdam()
{
return View();
}
[HttpPost]
public ActionResult Amsterdam(Amsterdam list)
{
string timeToday = DateTime.Now.ToString("h:mm:ss tt");
string dateToday = DateTime.Now.ToString("M/dd/yyyy");
if (ModelState.IsValid)
{
using (var db = new MainDbContext())
{
Claim sessionEmail = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email);
string userEmail = sessionEmail.Value;
var userIdQuery = db.Users.Where(u => u.Email == userEmail).Select(u => u.Id);
var userId = userIdQuery.ToList();
var dbAmsterdam = db.Amsterdam.Create();
dbAmsterdam.Details = list.Details;
dbAmsterdam.Date_Posted = dateToday;
dbAmsterdam.Time_Posted = timeToday;
dbAmsterdam.User_Id = userId[0];
db.Amsterdam.Add(dbAmsterdam);
db.SaveChanges();
}
}
else
{
ModelState.AddModelError("", "Incorrect format has been placed");
}
return View();
}
I know I got close because my register does work but I can't get my CRUD for Amsterdam to work. When I click ok as shown in the screenshot (when I click on Ad Item):
https://i.stack.imgur.com/XsGws.png
I get an error
DbUpdateException was unhandled by user code
https://i.stack.imgur.com/I6kYP.png
It appears that EF is doing pluralization of your object name to define the table name in the database (from the error - Invalid object name dbo.Amsterdams).
If your table name is Amsterdam (singular, without the trailing "s"), then add this data annotation to your model class:
[Table("Amsterdam")]
public class Amsterdam
{
[Key]
public int Id { get; set; }
.....
}
And if you want to turn off that pluralization of table names completely, you can add this line to your MainDbContext class:
protected override void OnModelCreating(DbModelBuilder dbModelBuilder)
{
dbModelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}

Model not getting bound to the view in asp.net MVC

I am trying to display a list of Providers in a table.The code to get the list of providers is as follows
public ActionResult Index()
{
DAL2 dal = new DAL2();
Provider patientlist = new Provider();
List<Provider> providers = dal.GetListofProviders.ToList();
return View(providers);
}
The above code is working fine.I am getting the list of providers as expected.
The HTML code in the view is as follows
#model IEnumerable<ProviderDemo.Models.Provider>
#{
ViewBag.Title = "ProviderList";
}
<head>
<title>LIST OF PROVIDERS</title>
</head>
<body>
<table class="table table-striped table-bordered table-hover">
<tr>
<th>Provider Type</th>
<th>First Name</th>
<th>Last Name</th>
<th>Certification</th>
<th>Specialization</th>
<th>SSN</th>
<th>Facility Name</th>
<th>Contact No</th>
<th>Contact Email</th>
<th></th>
</tr>
<tbody data-bind="foreach: viewmodel">
<tr>
<td class="col-lg-2" data-bind="text: ProviderType"></td>
<td class="col-lg-1" data-bind="text: FirstName"></td>
<td class="col-lg-1" data-bind="text: LastName"></td>
<td class="col-lg-1" data-bind="text: Certification"></>
<td class="col-lg-1" data-bind="text: Specialization"></td>
<td class="col-lg-1" data-bind="text: SSN"></td>
<td class="col-lg-4" data-bind="text: FacilityName"></td>
<td class="col-lg-4" data-bind="text: ContactNumber"></td>
<td class="col-lg-1" data-bind="text: ContactEmail"></td>
<td><a class="btn btn-default" id="del" onclick = "return confirm('Are you sure, you want to delete');" data-bind="attr: { href: '/ProviderRegister/Delete/' + ProviderID }"> Delete </a>
</td>
</tr>
</tbody>
</table>
</body>
My Provider class is as follows:
public class Provider
{
public int ProviderID { get; set; }
public string ProviderType { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Certification { get; set; }
public string Specialization { get; set; }
public string SSN { get; set; }
public string ContactNumber { get; set; }
public string ContactEmail { get; set; }
public string FacilityName { get; set; }
}
Provider Viewmodel
var Provider =
{
ProviderID:ko.observable(""),
ProviderType: ko.observable(""),
FirstName: ko.observable(""),
LastName: ko.observable(""),
Certification: ko.observable(""),
Specialization: ko.observable(""),
SSN: ko.observable(""),
ContactNumber: ko.observable(""),
ContactEmail: ko.observable(""),
FacilityName: ko.observable(""),
}
ko.applyBindings(Provider);
The list is not getting displayed in the table.There seems to be an error at the top of the html for the model.I dont understand why though.Am I doing something wrong here?Please guide me in the right direction.
Thanks a lot for all your help guys,but I made a mistake earlier.In the Index action ,I see the list of providers but I dont get any data in the view.So,I have the data in the controller but not in the view.
If you have a populated Model, you need to get the data from that out into you knockout model. So either use System.Web.Helpers.Json.Encode() or make your own JSON in the view.
Then load that data into your knockout view model.
var data = #Json.Encode(Model);
var ViewModel = function(data) {
var self = this;
self.Providers = ko.observableArray(data);
};
var viewmodel = new ViewModel(data);
ko.applyBindings(viewmodel);
and then in your foreach, use Providers instead of viewmodel

Categories

Resources