Getting Empty Object in postman - c#

i get empty object and 200 response when i try to get the movies which are bought,
i can buy the movie but can not show it
here is the repository function
public async Task<IEnumerable<CartItem>> CartItems(int UserId)
{
return await (from cart in this.context.Cart
join cartItem in this.context.CartItem
on cart.Id equals cartItem.CartId
where cart.UserId == UserId
select new CartItem
{
Id = cartItem.Id,
MovieId = cartItem.MovieId,
mengde = cartItem.mengde,
CartId = cartItem.CartId,
}).ToListAsync();
}
and the controller
[HttpGet("CurrentUser")]
public int GetLoggetInUserId()
{
int id = Convert.ToInt32(HttpContext.User.FindFirstValue("UserId"));
return id;
}
[HttpGet("GetItems")]
public async Task<ActionResult<IEnumerable<CartItemDTO>>> CartItems()
{
try
{
int userId = GetLoggetInUserId();
// here we returned cartItem object
var cartItems = await this.shoping.CartItems(userId);
if (cartItems == null)
{
return NoContent();
}
var movies = await this.repository.GetAll();
if (movies == null)
{
throw new Exception("No products exist in the system");
}
var UserCartItems = cartItems.ConvertToDto(movies);
return Ok(UserCartItems);
}
catch (Exception ex)
{
_logger.LogError(ex, "the GET call to /api/user fieled");
return StatusCode(StatusCodes.Status500InternalServerError,
ex.Message);
}
}
and the interface
public interface IShoping
{
Task<CartItem> AddItem(CartItemToAddDto cartItemToAddDto);
Task<CartItem> DeleteItem(int Id);
Task<CartItem> GetItem(int id);
Task<IEnumerable<CartItem>> CartItems(int UserId);
Task<CartItem> UpdateItem(int Id, CartItemMengdeUpdate cartItemMengdeUpdate);
the buy function works but when i try to get all the bought movies i get an empty object
(https://i.stack.imgur.com/boAYK.png)

Related

Cannot apply indexing with [] to an expression of type "ISession"

Problem arises in this snippet, but i dont really know why(code is from a tutorial
https://www.youtube.com/watch?v=b0CrSerID1A&list=PLjCTEYO9N-j0wMr_p9j92lfgbY4E9c_Ds&index=16
PICTURE of problem
public string GetCartId(HttpContext context)
{
if (context.Session[CartSessionKey] == null)
{
if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
{
context.Session[CartSessionKey] =
context.User.Identity.Name;
}
else
{
Guid tempCartId = Guid.NewGuid();
context.Session[CartSessionKey] = tempCartId.ToString();
}
}
return context.Session[CartSessionKey].ToString();
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNetCore.Http;
namespace DogSupreme.Models
{
public class ShoppingCart
{
private ContextClass accsess = new ContextClass();
string ShoppingCartId { get; set; }
public const string CartSessionKey = "CartId";
public static ShoppingCart GetCart(HttpContext context)
{
var cart = new ShoppingCart();
cart.ShoppingCartId = cart.GetCartId(context);
return cart;
}
// Helper method to simplify shopping cart calls
public static ShoppingCart GetCart(Microsoft.AspNetCore.Mvc.Controller controller)
{
return GetCart(controller.HttpContext);
}
public void AddToCart(Product item)
{
var cartItem = accsess.Carts.SingleOrDefault(
c => c.CartId == ShoppingCartId
&& c.ItemId == item.ProductId);
if (cartItem == null)
{
cartItem = new Cart
{
ItemId = item.ProductId,
CartId = ShoppingCartId,
Count = 1,
DateCreated = DateTime.Now
};
accsess.Carts.Add(cartItem);
}
else
{
cartItem.Count++;
}
accsess.SaveChanges();
}
public int RemoveFromCart(int id)
{
var cartItem = accsess.Carts.Single(
cart => cart.CartId == ShoppingCartId
&& cart.RecordId == id);
int itemCount = 0;
if (cartItem != null)
{
if (cartItem.Count > 1)
{
cartItem.Count--;
itemCount = cartItem.Count;
}
else
{
accsess.Carts.Remove(cartItem);
}
accsess.SaveChanges();
}
return itemCount;
}
public void EmptyCart()
{
var cartItems = accsess.Carts.Where(
cart => cart.CartId == ShoppingCartId);
foreach (var cartItem in cartItems)
{
accsess.Carts.Remove(cartItem);
}
accsess.SaveChanges();
}
public List<Cart> GetCartItems()
{
return accsess.Carts.Where(
cart => cart.CartId == ShoppingCartId).ToList();
}
public int GetCount()
{
int? count = (from cartItems in accsess.Carts
where cartItems.CartId == ShoppingCartId
select (int?)cartItems.Count).Sum();
return count ?? 0;
}
public decimal GetTotal()
{
decimal? total = (from cartItems in accsess.Carts
where cartItems.CartId == ShoppingCartId
select (int?)cartItems.Count *
cartItems.Product.Price).Sum();
return total ?? decimal.Zero;
}
public int CreateOrder(Order order)
{
decimal orderTotal = 0;
var cartItems = GetCartItems();
foreach (var item in cartItems)
{
var orderDetail = new OrderDetail
{
ItemId = item.ItemId,
OrderId = order.OrderId,
UnitPrice = item.Product.Price,
Quantity = item.Count
};
orderTotal += (item.Count * item.Product.Price);
accsess.OrderDetails.Add(orderDetail);
}
order.Total = orderTotal;
accsess.SaveChanges();
EmptyCart();
return order.OrderId;
}
public string GetCartId(HttpContext context)
{
if (context.Session[CartSessionKey] == null)
{
if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
{
context.Session[CartSessionKey] =
context.User.Identity.Name;
}
else
{
Guid tempCartId = Guid.NewGuid();
context.Session[CartSessionKey] = tempCartId.ToString();
}
}
return context.Session[CartSessionKey].ToString();
}
public void MigrateCart(string userName)
{
var shoppingCart = accsess.Carts.Where(
c => c.CartId == ShoppingCartId);
foreach (Cart item in shoppingCart)
{
item.CartId = userName;
}
accsess.SaveChanges();
}
}
}
You can use extension methods (Microsoft.AspNetCore.Http.Extensions) to get or set string session keys:
public string GetCartId(HttpContext context)
{
var session = context.Session;
if (!session.Keys.Contains(CartSessionKey))
{
var userName = context.User.Identity.Name;
if (!string.IsNullOrWhiteSpace(userName))
{
session.SetString(CartSessionKey, userName);
}
else
{
Guid tempCartId = Guid.NewGuid();
session.SetString(CartSessionKey, tempCartId.ToString())
}
}
return session.GetString(CartSessionKey);
}
Otherwise you should manually convert strings to and from byte array
Slightly refactored code to split cartId generation from working with session:
public string GetCartId(HttpContext context)
{
​var cartId = context.Session.GetString(CartSessionKey);
​if (cartId == null)
​{
cartId = GetUserCartId(context.User.Identity.Name);
​context.Session.SetString(CartSessionKey, cartId);
​}
return cartId;
}
​private void GetUserCartId(string userName)
{
if (!string.IsNullOrWhiteSpace(userName))
return userName;
var tempCartId = Guid.NewGuid();
return tempCartId.ToString();
}

How can I root from the front end to my controller

I have a problem with a project for my school.
I want to hide a button if the connectedUser had already vote for a post.
my fonctions on my controller is obviously not use (I tried to put a Console.Writeline("blabla") to try but no "blabla" on my console so I guess it's a problem with my root but I don't understand how to do it properly
this is my button in the html :
<button [hidden]="getVoteForPostConnectedUserPlus(post.id)" mat-icon-button>
<mat-icon (click)="down(post.id)">arrow_drop_down</mat-icon>
</button>
this is my fonction in the ts file:
getVoteForPostConnectedUserPlus(postId : number){
this.postService.getVoteForPostConnectedUserPlus(postId, this.getCurrentUserId);
}
this is my fonction in post.service.ts :
public getVoteForPostConnectedUserPlus(postId : number , userId : number){
return this.http.get<boolean>(`${this.baseUrl}api/posts/getVoteForPostConnectedUserPlus/${postId}/${userId}`)
}
and this is in my controller :
[HttpGet("getVoteForPostConnectedUserPlus/{postId}/{authorId}")]
public async Task<ActionResult<bool>> getVoteForPostConnectedUserPlus(int postId, int UserId)
{
Console.WriteLine("blabla");
Console.WriteLine("post id =" + postId + "userId =" + UserId + "");
var vote = await _context.Votes.SingleOrDefaultAsync(v => v.PostId == postId && v.AuthorId == UserId && v.UpDown == 1);
Console.WriteLine(vote.AuthorId);
if (vote != null)
{
return true;
}
else
{
return false;
}
}
I spend hours to find where is my problem and I become crazy ! I probably didn't understood something to make my root so if someone can help me it would be great !
thank you
edit : here is all my PostsController.cs (as asked in a comment) :
using System;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using prid1920_projet.Models;
using PRID_Framework;
using Microsoft.AspNetCore.Authorization;
namespace prid1920_projet.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PostsController : ControllerBase
{
private readonly PridContext _context;
public PostsController(PridContext context)
{
_context = context;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<PostDTO>>> GetQuestions()
{
var questions = (from q in _context.Posts where q.ParentId == null select q);
return (await questions.ToListAsync()).ToDTO();
}
//[Authorized(Role.Admin)]
[HttpGet("{id}")]
public async Task<ActionResult<PostDTO>> GetById(int id)
{
var post = await _context.Posts.FindAsync(id);
if (post == null)
return NotFound();
return post.ToDTO();
}
[HttpPost]
public async Task<ActionResult<PostDTO>> PostPost(PostDTO data)
{
var userPseudo = User.Identity.Name;
var newPost = new Post()
{
Author = (from u in _context.Users where u.Pseudo == userPseudo select u).FirstOrDefault(),
Title = data.Title,
Body = data.Body,
Timestamp = DateTime.Now,
ParentId = data.parentId,
//postTags ??
};
_context.Posts.Add(newPost);
var res = await _context.SaveChangesAsyncWithValidation();
if (!res.IsEmpty)
return BadRequest(res);
return CreatedAtAction(nameof(GetById), new { id = newPost.Id }, newPost.ToDTO());
}
[AllowAnonymous]
[HttpPost("accept/{id}")]
public async Task<ActionResult<bool>> Accept(int id)
{
var post = await _context.Posts.FindAsync(id);
if (post == null)
return NotFound();
var postParent = await _context.Posts.FindAsync(post.ParentId);
if (postParent == null)
return NotFound();
postParent.AcceptedAnswerId = id;
var res = await _context.SaveChangesAsyncWithValidation();
if (!res.IsEmpty)
return false;
return true;
}
[AllowAnonymous]
[HttpPost("up/{postId}/{authorId}")]
public async Task<ActionResult<bool>> Up(int postId, int authorId)
{
var vote = await _context.Votes.SingleOrDefaultAsync(p => p.PostId == postId && p.AuthorId == authorId);
if (vote != null)
{
vote.UpDown = +1;
}
else
{
Vote newVote = new Vote()
{
UpDown = 1,
AuthorId = authorId,
PostId = postId
};
_context.Votes.Add(newVote);
}
var res = await _context.SaveChangesAsyncWithValidation();
if (!res.IsEmpty)
return false;
return true;
}
[AllowAnonymous]
[HttpPost("down/{postId}/{authorId}")]
public async Task<ActionResult<bool>> Down(int postId, int authorId)
{
var vote = await _context.Votes.SingleOrDefaultAsync(p => p.PostId == postId && p.AuthorId == authorId);
if (vote != null)
{
vote.UpDown = -1;
}
else
{
Vote newVote = new Vote()
{
UpDown = -1,
AuthorId = authorId,
PostId = postId
};
_context.Votes.Add(newVote);
}
var res = await _context.SaveChangesAsyncWithValidation();
if (!res.IsEmpty)
return false;
return true;
}
[AllowAnonymous]
[HttpPost("clear/{postId}/{authorId}")]
public async Task<ActionResult<bool>> Clear(int postId, int authorId)
{
var vote = await _context.Votes.SingleOrDefaultAsync(p => p.PostId == postId && p.AuthorId == authorId);
if (vote.UpDown == 1 || vote.UpDown == -1)
{
_context.Remove(vote);
}
var res = await _context.SaveChangesAsyncWithValidation();
if (!res.IsEmpty)
return false;
return true;
}
[HttpGet("getVoteForPostConnectedUserMinus/{postId}/{authorId}")]
public async Task<ActionResult<bool>> getVoteForPostConnectedUserMinus(int postId, int userId)
{
Console.WriteLine("prout");
Console.WriteLine("post id =" + postId + "userId =" + userId + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
var vote = await _context.Votes.SingleOrDefaultAsync(v => v.PostId == postId && v.AuthorId == userId && v.UpDown == -1);
Console.WriteLine(vote + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
if (vote != null)
{
return true;
}
else
{
return false;
}
}
[HttpGet("getVoteForPostConnectedUserPlus/{postId}/{authorId}")]
public async Task<ActionResult<bool>> getVoteForPostConnectedUserPlus(int postId, int UserId)
{
Console.WriteLine("blabla");
Console.WriteLine("post id =" + postId + "userId =" + UserId + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
var vote = await _context.Votes.SingleOrDefaultAsync(v => v.PostId == postId && v.AuthorId == UserId && v.UpDown == 1);
Console.WriteLine(vote.AuthorId + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
if (vote != null)
{
return true;
}
else
{
return false;
}
}
[HttpGet("{postId}/{authorId}")]
public async Task<ActionResult<bool>> getVoteForPostConnectedUser(int postId, int UserId)
{
Console.WriteLine("prout");
Console.WriteLine("post id =" + postId + "userId =" + UserId + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
var vote = await _context.Votes.SingleOrDefaultAsync(v => v.PostId == postId && v.AuthorId == UserId);
Console.WriteLine(vote.AuthorId + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
if (vote != null)
{
return true;
}
else
{
return false;
}
}
}
}
Here I think the basic idea is wrong. Agnular change detection will run on every event and will try to reeavluate your expression, and each time it will call you api. What you could do is
change HTML to a static varible
<button [hidden]="postIsHidden" mat-icon-button>
<mat-icon (click)="down(post.id)">arrow_drop_down</mat-icon>
</button>
and for the .ts file
postIsHidden:boolean=true
ngOnInit(){
this.getVoteForPostConnectedUserPlus(/*your post id*/)
}
getVoteForPostConnectedUserPlus(postId : number){
this.postService.getVoteForPostConnectedUserPlus(postId, this.getCurrentUserId)
.subscribe((result)=>this.postIsHidden);
}

How do I send a message to the view that a duplicate entry exists?

I have some code that is checking for possible duplicate entries. What I'm struggling with is where and what to put to let the user know - probably a modal of some sort, displaying the message that a duplicate user already exists.
Model
public void SaveUser(SearchRolesViewModel objSearchRolesViewModel, string userID)
{
USERACCOUNT objUserAccount = new USERACCOUNT
{
HPID = Convert.ToInt32(objSearchRolesViewModel.NewUserHealthPlans),
DOMAIN = "Aeth",
NTUSERID = objSearchRolesViewModel.User_Id,
ROLEID = Convert.ToInt32(objSearchRolesViewModel.UserRole),
FIRSTNAME = objSearchRolesViewModel.FirstName,
LASTNAME = objSearchRolesViewModel.LastName,
EMAIL = objSearchRolesViewModel.Email,
ACTIVE = true/*Convert.ToBoolean(objSearchRolesViewModel.ActiveStatus)*/,
DEFAULTPLANID = Convert.ToInt32(objSearchRolesViewModel.NewUserPrimaryHealthPlan),
CREATEID = userID.Substring(5).ToUpper(),
CREATEDATE = DateTime.Now,
UPDATEID = userID.Substring(5).ToUpper(),
UPDATEDATE = DateTime.Now
};
if (CheckforDuplicate(objUserAccount.NTUSERID, objUserAccount.HPID).Count == 0)
{
_context.USERACCOUNTs.Add(objUserAccount);
_context.SaveChanges();
}
else
{
WHAT GOES HERE
}
}
Controller
[HttpPost]
public ActionResult Submit(SearchRolesViewModel searchRolesViewModel)
{
try
{
SearchRolesModel objUser = new SearchRolesModel();
if (searchRolesViewModel.User_Id != string.Empty && searchRolesViewModel.NewUserHealthPlans != string.Empty && searchRolesViewModel.UserRole != string.Empty && searchRolesViewModel.NewUserPrimaryHealthPlan != string.Empty)
{
objUser.SaveUser(searchRolesViewModel, System.Web.HttpContext.Current.Session["UserID"].ToString());
ModelState.Clear();
ViewBag.Message = "User added successfully";
}
return UserDetails();
}
else
{
OR SHOULD IT GO HERE
}
catch (Exception)
{
throw ;
}
}
The simplest solution is to add a return value.
public bool SaveUser(SearchRolesViewModel objSearchRolesViewModel, string userID)
{
/* Snip */
bool duplicate = CheckforDuplicate(objUserAccount.NTUSERID, objUserAccount.HPID).Count == 0;
if (duplicate) return false;
_context.USERACCOUNTs.Add(objUserAccount);
_context.SaveChanges();
return true;
}
Then check the return value in your controller:
var ok = objUser.SaveUser(searchRolesViewModel, System.Web.HttpContext.Current.Session["UserID"].ToString());
if (ok)
{
ModelState.Clear();
ViewBag.Message = "User added successfully";
}
else
{
ViewBag.Message = "User not added.";
}
You can create a repository base with a few generic queries. E.g Add, GetAll, Find, Exists, Count and others. For more details https://medium.com/falafel-software/implement-step-by-step-generic-repository-pattern-in-c-3422b6da43fd
https://medium.com/#marekzyla95/generic-repository-pattern-implemented-in-net-core-with-ef-core-c7e088c9c58
for example, a possible implementation for a generic Exists method:
public bool Exists(Expression<Func<TEntity, bool>> func)
{
return _context.Set<TEntity>()
.Where(func)
.Any();
}
where TEntity will to be the model USERACCOUNT
[HttpPost]
public ActionResult Submit(SearchRolesViewModel searchRolesViewModel)
{
try
{
SearchRolesModel objUser = new SearchRolesModel();
if (searchRolesViewModel.User_Id != string.Empty && searchRolesViewModel.NewUserHealthPlans != string.Empty && searchRolesViewModel.UserRole != string.Empty && searchRolesViewModel.NewUserPrimaryHealthPlan != string.Empty)
{
//here we call the Exists method from an user repository to check for duplicate entries
var isDuplicated = _userRepository.Exists(user => user.NTUSERID == objUser.NTUSERID && user.HPID == objUser.HPID);
if(isDuplicated)
{
ViewBag.Message = "User exists already!";
Return Foo(); // return for the more appropriate page
}
else
{
objUser.SaveUser(searchRolesViewModel, System.Web.HttpContext.Current.Session["UserID"].ToString());
ModelState.Clear();
ViewBag.Message = "User added successfully";
return UserDetails();
}
}
}
catch (Exception)
{
throw ;
}
}

Error 1 Inconsistent accessibility: parameter type 'WingtipToys.Logic.ShoppingCartUpdate[]' is less accessible than method

Error 1 Inconsistent accessibility: parameter type 'WingtipToys.Logic.ShoppingCartUpdate[]' is less accessible than method 'WingtipToys.Logic.ShoppingCartActions.UpdateShoppingCartDatabase(string, WingtipToys.Logic.ShoppingCartUpdate[])' C:\Users\Toshiba\documents\visual studio 2013\Projects\WingtipToys\WingtipToys\Logic\ShoppingCartActions.cs 93 21 WingtipToys
I don't understand the error please help.
The code where error is showing is in the first line of the given code UpdateShoppingCartDatabase.
namespace WingtipToys.Logic
{
public class ShoppingCartActions : IDisposable
{
public string ShoppingCartId { get; set; }
private ProductContext _db = new ProductContext();
public const string CartSessionKey = "CartId";
public void AddToCart(int id)
{
// Retrieve the product from the database.
ShoppingCartId = GetCartId();
var cartItem = _db.ShoppingCartItems.SingleOrDefault(
c => c.CartId == ShoppingCartId && c.ProductId == id);
if (cartItem == null)
{
// Create a new cart item if no cart item exists.
cartItem = new CartItem
{
ItemId = Guid.NewGuid().ToString(),
ProductId = id,
CartId = ShoppingCartId,
Product = _db.Products.SingleOrDefault
(p => p.ProductID == id),
Quantity = 1,
DateCreated = DateTime.Now
};
_db.ShoppingCartItems.Add(cartItem);
}
else
{
// If the item does exist in the cart,
// then add one to the quantity.
cartItem.Quantity++;
}
_db.SaveChanges();
}
public void Dispose()
{
if (_db != null)
{
_db.Dispose();
_db = null;
}
}
public string GetCartId()
{
if (HttpContext.Current.Session[CartSessionKey] == null)
{
if (!string.IsNullOrWhiteSpace(HttpContext.Current.User.Identity.Name))
{
HttpContext.Current.Session[CartSessionKey] = HttpContext.Current.User.Identity.Name;
}
else
{
Guid tempCartId = Guid.NewGuid();
HttpContext.Current.Session[CartSessionKey] = tempCartId.ToString();
}
}
return HttpContext.Current.Session[CartSessionKey].ToString();
}
public List<CartItem> GetCartItems()
{
ShoppingCartId = GetCartId();
return _db.ShoppingCartItems.Where(
c => c.CartId == ShoppingCartId).ToList();
}
public decimal GetTotal()
{
ShoppingCartId = GetCartId();
// Multiply product price by quantity of that product to get
// the current price for each of those products in the cart.
// Sum all product price totals to get the cart total.
decimal? total = decimal.Zero;
total = (decimal?)(from cartItems in _db.ShoppingCartItems
where cartItems.CartId == ShoppingCartId
select (int?)cartItems.Quantity * cartItems.Product.UnitPrice).Sum();
return total ?? decimal.Zero;
}
public ShoppingCartActions GetCart(HttpContext context)
{
using (var cart = new ShoppingCartActions())
{
cart.ShoppingCartId = cart.GetCartId();
return cart;
}
}
public void UpdateShoppingCartDatabase(String cardId, ShoppingCartUpdate []
CartItemUpdates)
{
using (var db = new WingtipToys.Models.ProductContext())
{
try
{
int CartItemCount = CartItemUpdates.Count();
List<CartItem> myCart = GetCartItems();
foreach (var cartItem in myCart)
{
//Iterate through all rows within shopping cart list
for(int i = 0; i < CartItemCount; i++)
{
if (cartItem.Product.ProductID == CartItemUpdates[i].ProductId)
{
if (CartItemUpdates[i].PurchaseQuantity < 1 ||
CartItemUpdates[i].RemoveItem == true)
{
RemoveItem(CartId, cartItem.ProductId);
}
else
{
UpdateItem(CartId, cartItem.ProductId,
CartItemUpdates[i].PurchaseQuantity);
}
}
}
}
}
I think you'll need to provide more information to get a definite answer. Like what a ShoppingCartUpdate is and how its defined.
As the error message suggests, you have a difference in accessibility. This could mean that your ShoppingCartUpdate is declared internal (example) so it can't be used in a public method as something outside of the assembly is allowed to call UpdateShoppingCartDatabase, but not allowed to access ShoppingCartUpdate as it's marked internal (again example, need more information)

How to set up a "Details" page when parsing from XML file in ASP.NET MVC

I have an MVC VS2013 project querying an XML document.
The index action on my controller returns a list of Restaurants, and I need to be able to click the individual restaurants and open a details page which will show the respective properties of that Restaurant.
In previous projects querying from a sql database I would just call the db context, for example
Restaurant restaurant = db.Restaurants.Find(id);
but I am uncertain what the XML querying equivalent is.
Here is what I have so far.
Model:
[XmlRoot("EstablishmentCollection")]
public class Restaurant
{
[Key]
[XmlElement("FHRSID")]
public int? FHRSID { get; set; }
[XmlElement("BusinessName")]
public string BusinessName { get; set; }
[XmlElement("RatingValue")]
public int? RatingValue { get; set; }
[XmlElement("Hygiene")]
public int? HygieneScore { get; set; }
}
Controller:
public ActionResult Index()
{
IQueryable<Restaurant> Res = null;
try
{
var qy = xmlDoc.Descendants("EstablishmentDetail").Select(n => new Restaurant()
{
FHRSID = (int)n.Element("FHRSID"),
BusinessName = n.Element("BusinessName").Value,
RatingValue = RValue(n),
HygieneScore = HScores(n)
});
Res = qy.AsQueryable();
}
catch (Exception ex)
{
string message;
message = ex.Message.ToString();
return View(message);
}
return View(Res);
}
public ActionResult Details (int? id)
{
try
{
var qy = xmlDoc.Descendants("EstablishmentDetail").Select(n => new Restaurant()
{
FHRSID = (int)n.Element("FHRSID"),
BusinessName = n.Element("BusinessName").Value,
RatingValue = RValue(n),
HygieneScore = HScores(n)
});
//What goes here???
}
catch (Exception ex)
{
string message;
message = ex.Message.ToString();
return View(message);
}
return View();
}
Details View:
#model WebApplication3.Models.Restaurant
<h2>Details</h2>
<h6>#Model.FHRSID</h6>
<h6>#Model.BusinessName</h6>
<h6>#Model.HygieneScore</h6>
<h6>#Model.RatingValue</h6>
EDIT:
I have been working on it, is something like the below heading in the right direction?
(Controller)
public ActionResult Details (int? id)
{
var qy = xmlDoc.Descendants("EstablishmentDetail").Select(n => new Restaurant()
{
FHRSID = (int)n.Element("FHRSID"),
BusinessName = n.Element("BusinessName").Value,
RatingValue = RValue(n),
HygieneScore = HScores(n)
}).ToList();
var query = from x in qy
where x.FHRSID == id
select new Restaurant();
return View(query);
}
Problem with the above is that I am having issues correctly sending the query to the view
var r = xmlDoc.Descendants("EstablishmentDetail")
.Select(n => new Restaurant()
{
FHRSID = (int)n.Element("FHRSID"),
BusinessName = n.Element("BusinessName").Value,
RatingValue = RValue(n),
HygieneScore = HScores(n)
})
.Single(r => r.FHRSID == id);
Single, SignleOrDefault, First, FirstOrDefault returns an element from a collection.

Categories

Resources