I'm trying to get a value session and add it into a table
here is my code i tried to get value :
public ActionResult CheckOut(FormCollection form)
{
try
{
Cart cart = Session["Cart"] as Cart;
OrderPro _order = new OrderPro();//Bảng hóa đơn sản phẩm
_order.DateOrder = DateTime.Now;
_order.AddressDeliverry = form["AddressDelivery"];
_order.IDCus = Convert.ToInt32(Session["ID"]);
db.OrderProes.Add(_order);
foreach (var item in cart.Items)
{
OrderDetail _order_detail = new OrderDetail();
_order_detail.IDOrder = _order.ID;
_order_detail.IDProduct = item.product.ProductID;
_order_detail.UnitPrice = (double)item.product.Price;
_order_detail.Quantity = item.quantity;
db.OrderDetails.Add(_order_detail);
}
db.SaveChanges();
cart.ClearCart();
return RedirectToAction("CheckOut_Success", "GioHang");
}
catch
{
return Content("<script language='javascript' type='text/javascript'>alert('Đã xảy ra lỗi, vui lòng kiểm tra thông tin');</script>");
}
}
here is the code Session :
public ActionResult Login(CustomerUser cus)
{
var check = db.CustomerUsers.Where(s => s.NameUser == cus.NameUser && s.PasswordUser == cus.PasswordUser).FirstOrDefault();
if(check == null)
{
ViewBag.ErrorLogin = "Sai info đăng nhập";
return View("Index");
}
else
{
db.Configuration.ValidateOnSaveEnabled = false;
Session["NameUser"] = cus.NameUser;
Session["PasswordUser"] = cus.PasswordUser;
Session["ID"] = cus.ID;
return RedirectToAction("DichVu", "Product");
}
}
Here is the model Session ID :
public partial class CustomerUser
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public CustomerUser()
{
this.OrderProes = new HashSet<OrderPro>();
}
public int ID { get; set; }
public string NameUser { get; set; }
public string PasswordUser { get; set; }
public string PhoneUser { get; set; }
public string EmailUser { get; set; }
}
i tried to debug but i get a error like this
enter image description here
Related
In my ASP.NET Core 6 Web API using Entity Framework, I am working on an Employee Leave Application.
And I have this model class:
public class EmployeeLeave
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public virtual Employee Employee { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public LeaveType LeaveType { get; set; }
public bool? IsCurrent { get; set; }
}
Then I also created some DTO as shown here:
public class LeaveRequestDto
{
public Guid EmployeeId { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public LeaveType LeaveType { get; set; }
}
public class LeaveResponseDto
{
public EmployeeResponseDto Employee { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string LeaveType { get; set; }
public bool? IsCurrent { get; set; }
}
Then I have the service for the implementation.
Interface:
Task<GenericResponseDto<LeaveResponseDto>> CreateAsync(LeaveRequestDto request);
Implementation:
public async Task<GenericResponseDto<LeaveResponseDto>> CreateAsync(LeaveRequestDto request)
{
var response = new GenericResponseDto<LeaveResponseDto>();
var employee = await _context.Employees.FirstOrDefaultAsync(e => e.Id == request.EmployeeId);
if (employee == null)
{
response.Error = new ErrorResponseDto()
{
ErrorCode = 404,
Message = "Employee does not exist in the system!"
};
response.StatusCode = 404;
}
else
{
var leave = _mapper.Map<EmployeeLeave>(request);
leave.Employee = employee;
leave.IsCurrent = true;
try
{
_context.EmployeeLeaves.Add(leave);
await _context.SaveChangesAsync();
response.Result = _mapper.Map<LeaveResponseDto>(leave);
response.StatusCode = 201;
}
catch (Exception ex)
{
response.Error = new ErrorResponseDto()
{
ErrorCode = 500,
Message = ex.Message
};
response.StatusCode = 500;
}
}
return response;
}
Currently, what I have will insert a new record for the Employee Leave Application into the database.
What I want to achieve is that I want to keep all the records of the Leave Applications for each employee.
At the point of insert, the application should check the last leave application record of that particular employee, change isCurrent to false, and then insert a new record, and the new record will have isCurrent as true.
How do I achieve this?
Thanks
You can retrieve the last record using LastOrDefault() and update it using EntityState.Modified
Try this
public async Task<GenericResponseDto<LeaveResponseDto>> CreateAsync(LeaveRequestDto request)
{
var response = new GenericResponseDto<LeaveResponseDto>();
var employee = await _context.Employees.FirstOrDefaultAsync(e => e.Id == request.EmployeeId);
if (employee == null)
{
response.Error = new ErrorResponseDto()
{
ErrorCode = 404,
Message = "Employee does not exist in the system!"
};
response.StatusCode = 404;
}
else
{
var lastLeave = _context.Set<EmployeeLeave>().where(leave =>
leave.Employee.Id == request.EmployeeId ).LastOrDefault();
if(lastLeave != null)
{
lastLeave .IsCurrent = false;
_context.Entry(lastLeave).State = EntityState.Modified;
}
var leave = _mapper.Map<EmployeeLeave>(request);
leave.Employee = employee;
leave.IsCurrent = true;
try
{
_context.EmployeeLeaves.Add(leave);
await _context.SaveChangesAsync();
response.Result = _mapper.Map<LeaveResponseDto>(leave);
response.StatusCode = 201;
}
catch (Exception ex)
{
response.Error = new ErrorResponseDto()
{
ErrorCode = 500,
Message = ex.Message
};
response.StatusCode = 500;
}
}
return response;
}
hello community I am implementing a system to audit the modifications that are made in my application carry out the process that is described in this article:
https://codewithmukesh.com/blog/audit-trail-implementation-in-aspnet-core/?unapproved=50671&moderation-hash=71700d12d4ebaf51ad9d90c4a9834324#comment-50671
but I don't know how to get the login of my application, to login I use web token and authentication provider.
any suggestion how to do it? I don't know if it can be done with serilog or something similar
this is my code:
public class Audit
{
public int Id { get; set; }
public string UserId { get; set; }
public string Type { get; set; }
public string TableName { get; set; }
public DateTime DateTime { get; set; }
public string OldValues { get; set; }
public string NewValues { get; set; }
public string AffectedColumns { get; set; }
public string PrimaryKey { get; set; }
}
public enum AuditType
{
None = 0,
Create = 1,
Update = 2,
Delete = 3
}
public class AuditEntry
{
public AuditEntry(EntityEntry entry)
{
Entry = entry;
}
public EntityEntry Entry { get; }
public string UserId { get; set; }
public string TableName { get; set; }
public Dictionary<string, object> KeyValues { get; } = new Dictionary<string, object>();
public Dictionary<string, object> OldValues { get; } = new Dictionary<string, object>();
public Dictionary<string, object> NewValues { get; } = new Dictionary<string, object>();
public AuditType AuditType { get; set; }
public List<string> ChangedColumns { get; } = new List<string>();
public Audit ToAudit()
{
var audit = new Audit();
audit.UserId = UserId;
audit.Type = AuditType.ToString();
audit.TableName = TableName;
audit.DateTime = DateTime.Now;
audit.PrimaryKey = JsonConvert.SerializeObject(KeyValues);
audit.OldValues = OldValues.Count == 0 ? null : JsonConvert.SerializeObject(OldValues);
audit.NewValues = NewValues.Count == 0 ? null : JsonConvert.SerializeObject(NewValues);
audit.AffectedColumns = ChangedColumns.Count == 0 ? null : JsonConvert.SerializeObject(ChangedColumns);
return audit;
}
}
public abstract class AuditableIdentityContext : IdentityDbContext
{
public AuditableIdentityContext(DbContextOptions options) : base(options)
{
}
public DbSet<Audit> AuditLogs { get; set; }
public virtual async Task<int> SaveChangesAsync(string userId = null)
{
OnBeforeSaveChanges(userId);
var result = await base.SaveChangesAsync();
return result;
}
private void OnBeforeSaveChanges(string userId)
{
ChangeTracker.DetectChanges();
var auditEntries = new List<AuditEntry>();
foreach (var entry in ChangeTracker.Entries())
{
if (entry.Entity is Audit || entry.State == EntityState.Detached || entry.State == EntityState.Unchanged)
continue;
var auditEntry = new AuditEntry(entry);
auditEntry.TableName = entry.Entity.GetType().Name;
auditEntry.UserId = userId;
auditEntries.Add(auditEntry);
foreach (var property in entry.Properties)
{
string propertyName = property.Metadata.Name;
if (property.Metadata.IsPrimaryKey())
{
auditEntry.KeyValues[propertyName] = property.CurrentValue;
continue;
}
switch (entry.State)
{
case EntityState.Added:
auditEntry.AuditType = Enums.AuditType.Create;
auditEntry.NewValues[propertyName] = property.CurrentValue;
break;
case EntityState.Deleted:
auditEntry.AuditType = Enums.AuditType.Delete;
auditEntry.OldValues[propertyName] = property.OriginalValue;
break;
case EntityState.Modified:
if (property.IsModified)
{
auditEntry.ChangedColumns.Add(propertyName);
auditEntry.AuditType = Enums.AuditType.Update;
auditEntry.OldValues[propertyName] = property.OriginalValue;
auditEntry.NewValues[propertyName] = property.CurrentValue;
}
break;
}
}
}
foreach (var auditEntry in auditEntries)
{
AuditLogs.Add(auditEntry.ToAudit());
}
}
}
I use a custom Controller that inherits from the built-in Controller, and added a CurrentUserName property. The problem is that Controller.User is not yet initialized in the Controller constructor. I override Controller.OnActionExecuting(), where the User exists, and use that to set my custom property.
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var authenticatedUser = User;
if (authenticatedUser != null)
{
string userId = authenticatedUser.FindFirstValue(ClaimTypes.NameIdentifier);
if (userId != null)
{
_currentUserId = int.Parse(userId, CultureInfo.InvariantCulture);
string userName = authenticatedUser.FindFirstValue(ClaimTypes.Name);
_context.CurrentUserName = userName;
_userIsAdmin = authenticatedUser.IsInRole(ConferenceRoleTypes.WebAdmin);
}
}
base.OnActionExecuting(filterContext);
}
i want to loop my request and perform something for my array ( Cart ) but i dont know how to loop the request
here is the request
enter image description here
and here is the object class or the model for the request
public class OrderRRModel
{
public ObjectId id { get; set; }
public string cutomer_name { get; set; }
public string table_number { get; set; }
public List<ListCart> Cart { get; set; }
public OrderRRModel()
{
Cart = new List<ListCart>();
}
}
public class ListCart
{
public string product { get; set; }
public double amount { get; set; }
public double price { get; set; }
}
here is my full code
public ResponseModel<OrderRRModel> InsertOrderTest(string tokenAdmin, OrderRRModel entity)
{
var entityResult = new ResponseModel<OrderRRModel>();
try
{
var auth = _adminCollection.Find(x => x.token == tokenAdmin).FirstOrDefault();
if (auth != null)
{
var dates = DateTime.Now.ToUniversalTime();
// looping here
var check = _menuCollection.Find(x => x.product_name == cart.product_name).FirstOrDefault();
cart.price = check.price;
var result = _menuCollection.UpdateOne(
x => x.product_name == cart.product_name,
Builders<MenuRRModel>.Update.Set(x => x.updated_at, dates)
.Set(x => x.stock, check.stock - cart.amount) // updating stock by reducing stock based on quantity
);
// end of looping
_orderCollection.InsertOne(entity);
entityResult.Status = true;
entityResult.Messages.Add(new ResponseMessageModel()
{
Type = ResponseMessageModel.MessageType.SUCCESS,
Title = "Success",
Message = "Successful"
});
}
else
{
entityResult.Messages.Add(new ResponseMessageModel()
{
Type = ResponseMessageModel.MessageType.WARNING,
Title = "Action Failed",
Message = "Anda Tidak Memiliki Wewenang!"
});
}
}
catch (Exception ex)
{
entityResult.Messages.Add(new ResponseMessageModel()
{
Type = ResponseMessageModel.MessageType.ERROR,
Title = "Error",
Message = ex.Message
});
}
return entityResult;
}
can you guys tell me the code for looping my request ?
please be kind im a newbie
just do this
foreach (var cart in entity.cart)
{
cart.itemcart
}
Hello I have a 'RestrictAccessController' That looks like this
public class RestrictAccessController : Controller
{
private PIC_Program_1_0Context db = new PIC_Program_1_0Context();
public ActionResult Index()
{
return View ();
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple=true)]
public class RestrictAccessAttribute : ActionFilterAttribute
{
private PIC_Program_1_0Context db = new PIC_Program_1_0Context();
public AccessRestrictions restriction { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
// here's where we check that the current action is allowed by the current user
if (!IGT.canAccess(IGT.userId, restriction, false))
{
string url = IGT.baseUrl+"/Home/NotAllowed";
string msg = "This page requires " + IGT.DisplayEnum(restriction) + " access";
filterContext.Result = new RedirectResult("~/Home/NotAllowed?msg="+HttpUtility.HtmlEncode(msg));
}
}
And a Config model that looks like this
public enum AccessRestrictions
{
[Display(Name = "Disposal Orders")]
ModifyDisposalOrder,
[Display(Name = "Admin")]
Admin
}
public class userAccess
{
[Key]
public int ID { get; set; }
public AccessRestrictions restriction { get; set; }
public bool allow { get; set; }
public int userID { get; set; }
}
public class configDetails
{
public int ID {get; set;}
public string Name {get; set;}
public string Value {get;set;}
public bool deleted {get;set;}
public DateTime updateTime { get; set; }
}
public class Config
{
public int ID { get; set; }
[Display(Name = "Configuration Date")]
public DateTime TargetDate { get; set; }
[Display(Name = "Enable Access Restrictions")]
public bool restrictAccess { get; set; }
}
What I want to do is edit what my 'ChangeStatus' dropdown looks like based on whether they have the Admin access restriction or not. Here is the controller method that I want to edit
[RestrictAccess(restriction = AccessRestrictions.ModifyDisposalOrder)]
public ActionResult ChangeStatus(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DisposalOrder disposalOrder = db.disposalOrders.Find(id);
if (disposalOrder == null)
{
return HttpNotFound();
}
switch (disposalOrder.Status)
{
case DOStatus.Pending:
ViewBag.statusList = new List<Object>
{
new {value = DOStatus.Pending, text = "Pending"},
new {value = DOStatus.Disposed, text = "Disposed" }
};
break;
case DOStatus.Disposed:
// if(restriction = AccessRestrictions.ModifyDisposalOrder)
ViewBag.statusList = new List<Object>
{
new {value = DOStatus.Pending, text = "Pending"},
new {value = DOStatus.Disposed, text = "Disposed" }
};
//else
//{
// new { value = DOStatus.Disposed, text = "Disposed" }
// };
break;
};
return View(disposalOrder);
}
Here is my Startup file
public class LdapAuthentication
{
private string _adUser = ConfigurationManager.AppSettings["ADUserName"];
private string _adPW = ConfigurationManager.AppSettings["ADPassword"];
private string _domain = ConfigurationManager.AppSettings["ADDomain"];
public LdapAuthentication() {
}
public string authenticate(string username, string pwd)
{
using (var context = new PrincipalContext(ContextType.Domain, _domain, _adUser, _adPW)) {
//Username and password for authentication.
if (context.ValidateCredentials(username, pwd)) {
UserPrincipal user = UserPrincipal.FindByIdentity(context, username);
Internal internalUser = new Internal {
UserName = user.SamAccountName,
ContactName = user.DisplayName,
Email = user.UserPrincipalName
};
//Search if the user account already exists in the database
PIC_Program_1_0Context db = new PIC_Program_1_0Context();
Internal existing = db.Internals.Where(x => x.UserName == user.SamAccountName).FirstOrDefault();
// If it does not, create a new user account
if (existing == null) {
// add a new Internal entry for this user
existing = new Internal {
UserName = user.SamAccountName,
ContactName = user.DisplayName,
Email = user.UserPrincipalName
};
db.Internals.Add(existing);
db.SaveChanges();
// If it does exist, but some of the data does not match, update the data
} else if(existing != internalUser) {
existing.ContactName = internalUser.ContactName;
existing.Email = internalUser.Email;
db.SaveChanges();
}
return user.SamAccountName;
} else {
return null;
}
}
}
public UserPrincipal getUserPrincipal(string username)
{
using (var context = new PrincipalContext(ContextType.Domain, _domain, _adUser, _adPW))
{
return UserPrincipal.FindByIdentity(context, username);
}
}
Is it possible for me to accomplish this?
Ok, I think I understand your question now. You need to access the User's claims. MVC Controllers have this, half way, built in.
if (User.HasClaim("ClaimNameHere", "Admin"))
{
}
Solved by adding
if (IGT.canAccess(IGT.userId, AccessRestrictions.Admin, false))
could anyone tell me what am I doing wrong? I am getting null properties trying to bind.
Explaining:
My Controller Index looks ok, so that in my View I can see all the input values that I want to bind filled (IdPedidoAtendimento,PedidoAtendimentoTaxa,HorarioAgendado,IdPedidoTipoPagamento,IdUnidadeUsuario).
So far, everything looks good. But, after submit the page, in my Controller CheckOut all the properties in checkOut object binded is null, as you can see in the picture.
It was working fine, I dont know what I did so that it now is getting null properties.
I am using asp.net core 3.1 MVC
ViewModel
public class CheckOut
{
public Usuario Usuario { get; set; }
public UsuarioUnidade UsuarioUnidade { get; set; }
public CatalogoEndereco CatalogoEndereco { get; set; }
public UsuarioPagamento UsuarioPagamento { get; set; }
public byte IdPedidoAtendimento { get; set; }
public string PedidoAtendimentoNome { get; set; }
public decimal PedidoAtendimentoTaxa { get; set; }
public DateTime? HorarioAgendado { get; set; }
public byte IdPedidoTipoPagamento { get; set; }
public string PedidoTipoPagamento { get; set; }
public int IdUnidadeUsuario { get; set; }
public string Nome { get; set; }
public string NumEndereco { get; set; }
public string ComplementoEndereco { get; set; }
public string RuaNome { get; set; }
public string CidadeNome { get; set; }
public string EstadoNome { get; set; }
public string CEP { get; set; }
public byte? isCPF { get; set; }
public string CPF { get; set; }
public string NumeroCartao { get; set; }
public string CodCartao { get; set; }
}
Controller
public IActionResult Index()
{
var user = User.FindFirst(ClaimTypes.Name);
if (user != null)
{
Usuario usuario = new Usuario();
usuario = _context.Usuario
.SingleOrDefault(u => u.Email.Equals(user.Value) && u.IsAtivo == true);
CatalogoEndereco catalogoEndereco = new CatalogoEndereco();
catalogoEndereco = _context.CatalogoEndereco
.Where(c => c.IdUsuario.Equals(usuario.IdUsuario) && c.IsAtivo == true && c.IsPrincipal == true)
.SingleOrDefault();
UsuarioPagamento usuarioPagamento = new UsuarioPagamento();
usuarioPagamento = _context.UsuarioPagamento
.Where(c => c.IdUsuario.Equals(usuario.IdUsuario) && c.IsPrincipal == true)
.SingleOrDefault();
UsuarioUnidade usuarioUnidade = new UsuarioUnidade();
usuarioUnidade = _context.UsuarioUnidade
.Where(c => c.IdUsuario.Equals(usuario.IdUsuario) && c.IdUnidadeNavigation.IsAtiva == true && c.IsPrincipal == true)
.SingleOrDefault();
UsuarioAtendimento usuarioAtendimento = new UsuarioAtendimento();
usuarioAtendimento = _context.UsuarioAtendimento
.Where(c => c.IdUsuario.Equals(usuario.IdUsuario) && c.IsPrincipal == true)
.SingleOrDefault();
CheckOut checkOut = new CheckOut()
{
Usuario = usuario,
UsuarioUnidade = usuarioUnidade,
CatalogoEndereco = catalogoEndereco,
UsuarioPagamento = usuarioPagamento,
IdPedidoAtendimento = usuarioAtendimento.Tipo,
PedidoAtendimentoNome = _context.PedidoAtendimento
.FirstOrDefault(t => t.IdPedidoAtendimento == usuarioAtendimento.Tipo).Nome,
PedidoAtendimentoTaxa = _context.PedidoAtendimento
.FirstOrDefault(t => t.IdPedidoAtendimento == usuarioAtendimento.Tipo).Taxa
};
if (usuarioAtendimento.Tipo == 1)
{
checkOut.Nome = usuario.Nome;
if (usuarioUnidade != null)
{
checkOut.IdUnidadeUsuario = usuarioUnidade.IdUnidade;
}
if (catalogoEndereco != null)
{
checkOut.RuaNome = catalogoEndereco.IdEnderecoLogradouroNavigation.IdRuaNavigation.Nome;
checkOut.CidadeNome = catalogoEndereco.IdEnderecoLogradouroNavigation.IdCidadeNavigation.Nome;
checkOut.EstadoNome = catalogoEndereco.IdEnderecoLogradouroNavigation.IdEstadoNavigation.Nome;
checkOut.NumEndereco = catalogoEndereco.NumEndereco;
checkOut.ComplementoEndereco = catalogoEndereco.Complemento;
checkOut.CEP = catalogoEndereco.IdEnderecoLogradouroNavigation.Cep;
}
}
else if (usuarioAtendimento.Tipo == 2)
{
if (usuarioUnidade != null)
{
checkOut.IdUnidadeUsuario = usuarioUnidade.IdUnidade;
checkOut.Nome = usuarioUnidade.IdUnidadeNavigation.Nome;
checkOut.RuaNome = usuarioUnidade.IdUnidadeNavigation.IdEnderecoLogradouroNavigation.IdRuaNavigation.Nome;
checkOut.CidadeNome = usuarioUnidade.IdUnidadeNavigation.IdEnderecoLogradouroNavigation.IdCidadeNavigation.Nome;
checkOut.EstadoNome = usuarioUnidade.IdUnidadeNavigation.IdEnderecoLogradouroNavigation.IdEstadoNavigation.Nome;
checkOut.NumEndereco = usuarioUnidade.IdUnidadeNavigation.NumEndereco;
checkOut.CEP = usuarioUnidade.IdUnidadeNavigation.IdEnderecoLogradouroNavigation.Cep;
}
}
if (usuarioPagamento != null)
{
checkOut.IdPedidoTipoPagamento = usuarioPagamento.Tipo;
checkOut.PedidoTipoPagamento = _context.PedidoTipoPagamento
.FirstOrDefault(t => t.IdPedidoTipoPagamento == usuarioPagamento.Tipo).Nome;
checkOut.isCPF = 0;
checkOut.CPF = usuario.Cpf;
checkOut.NumeroCartao = null;
checkOut.CodCartao = null;
if (usuarioPagamento.Tipo == 1 || usuarioPagamento.Tipo == 2)
{
checkOut.NumeroCartao = "**** " + usuarioPagamento.Numero.Substring(12, 4);
checkOut.CodCartao = null;
}
}
return View(checkOut);
}
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CheckOut([Bind("IdPedidoAtendimento,PedidoAtendimentoTaxa,HorarioAgendado,IdPedidoTipoPagamento,IdUnidadeUsuario")] CheckOut checkOut)
{
if (ModelState.IsValid)
{
var user = User.FindFirst(ClaimTypes.Name);
if (user != null)
{
var cliente = _context.Usuario.SingleOrDefault(u => u.Email.Equals(user.Value));
var pedido = new Pedido()
{
IdUsuario = cliente.IdUsuario,
IdUnidade = checkOut.IdUnidadeUsuario,
IdPedidoCanalVenda = 1,
IdPedidoAtendimento = checkOut.IdPedidoAtendimento,
IdAtendente = null,
IdPedidoTipoPagamento = checkOut.IdPedidoTipoPagamento,
IdEntregador = null,
IdPedidoStatus = 1,
DataPedido = DateTime.Now,
DataEntrega = null,
HorarioAgendado = null,
TaxaServico = checkOut.PedidoAtendimentoTaxa
};
_context.Pedido.Add(pedido);
await _context.SaveChangesAsync()
.ConfigureAwait(false);
int lastPedido = pedido.IdPedido;
List<Carrinho> cart = JsonSerializeSessionHelper.Get<List<Carrinho>>(HttpContext.Session, "cart");
foreach (var item in cart)
{
var pedidoItens = new PedidoItens
{
IdPedido = lastPedido,
IdProduto = item.IdProduto,
IdProdutoTamanho = item.IdProdutoTamanho,
IdProdutoTipoMassa = item.IdProdutoTipoMassa,
IdProdutoMeia = item.IdProdutoMeia,
Quantidade = item.Quantidade,
Preco = item.Preco
};
_context.PedidoItens.Add(pedidoItens);
}
await _context.SaveChangesAsync()
.ConfigureAwait(false);
TempData["save"] = "Pedido realizado com sucesso";
HttpContext.Session.Remove("cart");
}
else
{
return RedirectToAction("Index", "Login");
}
return RedirectToAction("Index", "Pedido");
}
return View(checkOut);
}
View
#using (Html.BeginForm("CheckOut", "Carrinho", FormMethod.Post))
{
<button type="submit" class="btn btn-info btn-sm">
Pagar (R$ #(#ViewBag.SubTotal + Model.PedidoAtendimentoTaxa))
</button>
// I need these values for Bind!!
#*#Html.DisplayFor(m => m.IdPedidoAtendimento)
#Html.DisplayFor(m => m.PedidoAtendimentoTaxa)
#Html.DisplayFor(m => m.HorarioAgendado)
#Html.DisplayFor(m => m.IdPedidoTipoPagamento)
#Html.DisplayFor(m => m.IdUnidadeUsuario)*#
<input asp-for="IdPedidoAtendimento" value="#Model.IdPedidoAtendimento" id="txtIdPedidoAtendimento" name="txtIdPedidoAtendimento" hidden/>
<input asp-for="PedidoAtendimentoTaxa" value="#Model.PedidoAtendimentoTaxa" id="txtPedidoAtendimentoTaxa" name="txtPedidoAtendimentoTaxa" hidden/>
<input asp-for="HorarioAgendado" value="#Model.HorarioAgendado" id="txtHorarioAgendado" name="txtHorarioAgendado" hidden />
<input asp-for="IdPedidoTipoPagamento" value="#Model.IdPedidoTipoPagamento" id="txtIdPedidoTipoPagamento" name="txtIdPedidoTipoPagamento" hidden/>
<input asp-for="IdUnidadeUsuario" value="#Model.IdUnidadeUsuario" id="txtIdUnidadeUsuario" name="txtIdUnidadeUsuario" hidden/>
}
Model binding occurs based on the name attribute. You have the #Html.DisplayFor lines commented out, so it isn't binding there. For the <input> fields, you have manually entered a name of txt<PropertyName>, so it isn't binding on those, either.
ASP.NET will automatically create an appropriate name attribute just using the asp-for attribute to accommodate model binding.