MVC The INSERT statement conflicted with the FOREIGN KEY constraint - c#

When I try to create a ticket on my create.cshtml it gives me this error. I think it's because my Category uses a dropdownlist using ViewBags while my User and Administrator dropdown list doesn't.
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_dbo.Ticket_dbo.Category_CategoryID". The conflict occurred in
database "RecreationalServicesTicketingSystem.DAL.IssueContext", table
"dbo.Category", column 'CategoryID'. The statement has been
terminated.
TicketController.cs
public class TicketController : Controller
{
private IssueContext db = new IssueContext();
public ActionResult Create()
{
TicketVM model = new TicketVM();
ConfigureViewModel(model);
ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName");
ViewBag.AllUsers = db.Users.ToList().Select(u => new SelectListItem() { Value = u.UserID.ToString(), Text = string.Format("{0} {1}", u.FirstMidName, u.LastName) });
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(TicketVM model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model);
return View(model);
}
Ticket ticket = new Ticket
{
Issue = model.Issue,
IssuedTo = model.IssuedTo
};
if (ModelState.IsValid)
{
db.Tickets.Add(ticket);
ERROR------> db.SaveChanges(); <------ ERROR
return View();
}
ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", ticket.CategoryID);
ViewBag.AllUsers = db.Users.ToList().Select(u => new SelectListItem() { Value = u.UserID.ToString(), Text = string.Format("{0} {1}", u.FirstMidName, u.LastName) });
ViewBag.AllAdmins = db.Users.Where(u => u.IsAdministrator).Include(u => u.Tickets);
return View(ticket);
}
private void ConfigureViewModel(TicketVM model)
{
IEnumerable<User> admins = db.Users.Where(u => u.IsAdministrator).OrderBy(u => u.LastName);
model.AdministratorList = admins.Select(a => new SelectListItem
{
Value = a.UserID.ToString(),
Text = string.Format("{0} {1}", a.FirstMidName, a.LastName)
});
}
}
\Views\Ticket\Create.cshtml
#model RecreationalServicesTicketingSystem.ViewModels.TicketVM
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Ticket</legend>
<div class="editor-label">
#Html.LabelFor(model => model.CategoryID, "Category")
</div>
<div class="editor-field">
#Html.DropDownList("CategoryID", String.Empty)
#Html.ValidationMessageFor(model => model.CategoryID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.UserID, "User")
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.UserID, (IEnumerable<SelectListItem>)ViewBag.AllUsers, "Please select")`
#Html.ValidationMessageFor(model => model.UserID)
</div>
<div class="editor-field">
#using (Html.BeginForm())
{
#Html.HiddenFor(m => m.UserID)
<div class="form-group">
#Html.LabelFor(m => m.IssuedTo)
#Html.DropDownListFor(m => m.IssuedTo, Model.AdministratorList, "Please select", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.IssuedTo)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Issue)
#Html.TextBoxFor(m => m.Issue, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Issue)
</div>
}
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Category.cs
public class Category
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public virtual ICollection<Ticket> Tickets { get; set; }
}
Ticket.cs
public enum Priority
{
Low, Med, High
}
public class Ticket
{
public int? TicketID { get; set; }
[Required(ErrorMessage = "Please enter the description")]
public string Issue { get; set; }
[Display(Name = "Administrator")]
[Required(ErrorMessage = "Please select the Administrator")]
public int IssuedTo { get; set; }
public int Author { get; set; }
[DisplayFormat(NullDisplayText = "No Priority")]
public Priority? Priority { get; set; }
[ForeignKey("CategoryID")]
public virtual Category Category { get; set; }
public int CategoryID { get; set; }
public int UserID { get; set; }
[ForeignKey("UserID")]
public virtual User User { get; set; }
}
ViewModels\TicketVM.cs
public class TicketVM
{
public int? UserID { get; set; }
[Required(ErrorMessage = "Please enter the description")]
public string Issue { get; set; }
[Display(Name = "Administrator")]
[Required(ErrorMessage = "Please select the Administrator")]
public int IssuedTo { get; set; }
public IEnumerable<SelectListItem> AdministratorList { get; set; }
public int CategoryID { get; set; }
}
AccountController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using RecreationalServicesTicketingSystem.Filters;
using RecreationalServicesTicketingSystem.Models;
namespace RecreationalServicesTicketingSystem.Controllers
{
[Authorize]
[InitializeSimpleMembership]
public class AccountController : Controller
{
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
return RedirectToLocal(returnUrl);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
WebSecurity.Logout();
return RedirectToAction("Index", "Home");
}
//
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/Disassociate
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Disassociate(string provider, string providerUserId)
{
string ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
ManageMessageId? message = null;
// Only disassociate the account if the currently logged in user is the owner
if (ownerAccount == User.Identity.Name)
{
// Use a transaction to prevent the user from deleting their last login credential
using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
{
bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
{
OAuthWebSecurity.DeleteAccount(provider, providerUserId);
scope.Complete();
message = ManageMessageId.RemoveLoginSuccess;
}
}
}
return RedirectToAction("Manage", new { Message = message });
}
//
// GET: /Account/Manage
public ActionResult Manage(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: "";
ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
ViewBag.ReturnUrl = Url.Action("Manage");
return View();
}
//
// POST: /Account/Manage
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Manage(LocalPasswordModel model)
{
bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
ViewBag.HasLocalPassword = hasLocalAccount;
ViewBag.ReturnUrl = Url.Action("Manage");
if (hasLocalAccount)
{
if (ModelState.IsValid)
{
// ChangePassword will throw an exception rather than return false in certain failure scenarios.
bool changePasswordSucceeded;
try
{
changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
}
catch (Exception)
{
changePasswordSucceeded = false;
}
if (changePasswordSucceeded)
{
return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
}
else
{
ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
}
}
}
else
{
// User does not have a local password so remove any validation errors caused by a missing
// OldPassword field
ModelState state = ModelState["OldPassword"];
if (state != null)
{
state.Errors.Clear();
}
if (ModelState.IsValid)
{
try
{
WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
}
catch (Exception)
{
ModelState.AddModelError("", String.Format("Unable to create local account. An account with the name \"{0}\" may already exist.", User.Identity.Name));
}
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
}
//
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public ActionResult ExternalLoginCallback(string returnUrl)
{
AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
if (!result.IsSuccessful)
{
return RedirectToAction("ExternalLoginFailure");
}
if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
{
return RedirectToLocal(returnUrl);
}
if (User.Identity.IsAuthenticated)
{
// If the current user is logged in add the new account
OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
return RedirectToLocal(returnUrl);
}
else
{
// User is new, ask for their desired membership name
string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
ViewBag.ReturnUrl = returnUrl;
return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
{
string provider = null;
string providerUserId = null;
if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
{
return RedirectToAction("Manage");
}
if (ModelState.IsValid)
{
// Insert a new user into the database
using (UsersContext db = new UsersContext())
{
UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
// Check if user already exists
if (user == null)
{
// Insert name into the profile table
db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
db.SaveChanges();
OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
}
}
}
ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
ViewBag.ReturnUrl = returnUrl;
return View(model);
}
//
// GET: /Account/ExternalLoginFailure
[AllowAnonymous]
public ActionResult ExternalLoginFailure()
{
return View();
}
[AllowAnonymous]
[ChildActionOnly]
public ActionResult ExternalLoginsList(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return PartialView("_ExternalLoginsListPartial", OAuthWebSecurity.RegisteredClientData);
}
[ChildActionOnly]
public ActionResult RemoveExternalLogins()
{
ICollection<OAuthAccount> accounts = OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name);
List<ExternalLogin> externalLogins = new List<ExternalLogin>();
foreach (OAuthAccount account in accounts)
{
AuthenticationClientData clientData = OAuthWebSecurity.GetOAuthClientData(account.Provider);
externalLogins.Add(new ExternalLogin
{
Provider = account.Provider,
ProviderDisplayName = clientData.DisplayName,
ProviderUserId = account.ProviderUserId,
});
}
ViewBag.ShowRemoveButton = externalLogins.Count > 1 || OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
return PartialView("_RemoveExternalLoginsPartial", externalLogins);
}
#region Helpers
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
public enum ManageMessageId
{
ChangePasswordSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
}
internal class ExternalLoginResult : ActionResult
{
public ExternalLoginResult(string provider, string returnUrl)
{
Provider = provider;
ReturnUrl = returnUrl;
}
public string Provider { get; private set; }
public string ReturnUrl { get; private set; }
public override void ExecuteResult(ControllerContext context)
{
OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl);
}
}
private static string ErrorCodeToString(MembershipCreateStatus createStatus)
{
// See http://go.microsoft.com/fwlink/?LinkID=177550 for
// a full list of status codes.
switch (createStatus)
{
case MembershipCreateStatus.DuplicateUserName:
return "User name already exists. Please enter a different user name.";
case MembershipCreateStatus.DuplicateEmail:
return "A user name for that e-mail address already exists. Please enter a different e-mail address.";
case MembershipCreateStatus.InvalidPassword:
return "The password provided is invalid. Please enter a valid password value.";
case MembershipCreateStatus.InvalidEmail:
return "The e-mail address provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidAnswer:
return "The password retrieval answer provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidQuestion:
return "The password retrieval question provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidUserName:
return "The user name provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.ProviderError:
return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
case MembershipCreateStatus.UserRejected:
return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
default:
return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
}
}
#endregion
}
}
Models\AccountModels.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Globalization;
using System.Web.Security;
namespace RecreationalServicesTicketingSystem.Models
{
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
}
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
}
public class RegisterExternalLoginModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
public string ExternalLoginData { get; set; }
}
public class LocalPasswordModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class LoginModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class ExternalLogin
{
public string Provider { get; set; }
public string ProviderDisplayName { get; set; }
public string ProviderUserId { get; set; }
}
}

Related

Issue when editing a Users Role

I'm following a Book which shows you how to edit a users role. Everything's working fine until I get to a line of code. I think it will be a pretty simple solution, however, I cannot figure it out.
var result = await _userManager.AddToRoleAsync(user.Id,
selectedRole.Except(userRoles).ToArray<string>());
The line of code above is returning an error:
"Argument 2: cannot convert from 'string[]' to 'string'"
In the book, it shows:
.ToArray<string>
However, in my line of code, it's just telling me to refactor to:
.ToArray());
Is there another way of converting to string? I'll post the code below, thanks.
EDIT USER CODE
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> EditUser(EditUserViewModel model, params string[] selectedRole)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByIdAsync(model.Id);
if (user == null)
{
return HttpNotFound();
}
user.UserName = model.UserName;
user.FirstName = model.FirstName;
user.LastName = model.LastName;
var userRoles = await _userManager.GetRolesAsync(user.Id);
selectedRole = selectedRole ?? new string[] { };
var result = await _userManager.AddToRoleAsync(user.Id,
selectedRole.Except(userRoles).ToArray<string>()); // may not be right
if (!result.Succeeded)
{
ModelState.AddModelError("", result.Errors.First());
return View();
}
result = await _userManager.RemoveFromRoleAsync(user.Id, userRoles.Except(selectedRole).ToArray().ToString()); // put to string
if (!result.Succeeded)
{
ModelState.AddModelError("", result.Errors.First());
return View();
}
return RedirectToAction("Index");
}
ModelState.AddModelError("", "Something's failed.");
return View();
}
EditUserViewModel
public class EditUserViewModel
{
public string Id { get; set; }
[Required]
[Display(Name = "Username")]
public string UserName { get; set; }
[Required(AllowEmptyStrings = false)]
[Display(Name = "Email")]
[EmailAddress]
public string Email { get; set; }
[Required]
[Display(Name = "First Name")]
[StringLength(50)]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
[StringLength(50)]
public string LastName { get; set; }
public IEnumerable<SelectListItem> RolesList { get; set; }
}
EditUser View
<div class="form-group">
#Html.Label("Roles", new { #class = "control-label col-md-2" })
<span class="col-md-10">
#foreach (var item in Model.RolesList)
{
<input type="checkbox" name="SelectedRole" value="#item.Value"
checked="#item.Selected" class="checkbox-inline" />
#Html.Label(item.Value, new { #class = "control-label" })
}
</span>
</div>
If you want to convert to string you can use String.Join and as a separator use
string.Empty, null or whatever separator you want but will be included in your string.
string str = string.Join(string.Empty, yourArray)
It's a typo in the book or when copying from the book. It should be:
var result = await _userManager.AddToRolesAsync(user.Id,
selectedRole.Except(userRoles).ToArray<string>());
The AddToRolesAsync takes an IEnumerable<string> as its second parameter, AddToRoleAsync takes a string.

How to only save certain values in edit razor page

I currently have an edit page where I have an invoice. It is a picture saved as a binary value.
When I want to edit an invoice, I want the picture to stay the same but when I press save, it gets rid of the image and updates the row to null.
Would it possibly have something to do with my Edit Method?
Here is part of my razor page:
#{
ViewBag.Title = "Edit";
if (Model.PictureOfInvoice != null)
{
var base64 = Convert.ToBase64String(Model.PictureOfInvoice);
var imgsrc = string.Format("data:image/jpg;base64,{0}", base64);
<img src="#imgsrc" style="max-width:500px;max-height:500px" align="right" />
}
}
<h2>Details of Invoice</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Invoice</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.InvoiceId)
Is there any way for this not to be updated?
EDIT
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Invoice invoice = db.Invoices.Find(id);
if (invoice == null)
{
return HttpNotFound();
}
ViewBag.ChurchId = new SelectList(db.Churches, "ChurchId", "Name", invoice.ChurchId);
return View(invoice);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "InvoiceId,Company,Description,Amount,ChurchId")] Invoice invoice)
{
if (ModelState.IsValid)
{
db.Entry(invoice).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ChurchId = new SelectList(db.Churches, "ChurchId", "Name", invoice.ChurchId);
return View(invoice);
}
My Model:
public class Invoice
{
[Key]
public int InvoiceId { get; set; }
public string Company { get; set; }
public string Description { get; set; }
public decimal Amount { get; set; }
public byte[] PictureOfInvoice { get; set; }
public string ImageFileName { get; set; }
[ForeignKey("Church")]
public int ChurchId { get; set; }
public virtual Church Church { get; set; }
public virtual Administration Admins { get; set; }
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "InvoiceId,Company,Description,Amount,ChurchId")] Invoice invoice)
{
if (ModelState.IsValid)
{
Invoice oldInvoice = db.Invoices.Find(id);
oldInvoice.Amount = invoice.Amount;
// repeated for all of the properties (but not the image)
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ChurchId = new SelectList(db.Churches, "ChurchId", "Name", invoice.ChurchId);
return View(invoice);
}
The key is to use db.Invoices.Find to get the existing item out of the database. That way existing properties (like the image) won't be lost.

I make a login page and I want to show user info name Address etc when I successfully login

This is controller code for Login,
This is User Login Controller code where I authenticating user Email ID and password when user login redirected to Home Controller where I want to show user info
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(UserLogin login, string ReturnUrl = ""){
string message = "";
using (LoginEntities dc = new LoginEntities()){
var v = dc.Users.Where(a => a.EmailID == login.EmailID).FirstOrDefault();
var n = dc.Users.Where(a => a.Password == login.Password).FirstOrDefault();
if (v != null || n != null ){
if (string.Compare(Crypto.Hash(login.Password), v.Password) == 0){
int timeout = login.RememberME ? 525600 : 20;
var ticket = new FormsAuthenticationTicket(login.EmailID,login.RememberME,timeout);
string encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = DateTime.Now.AddMinutes(timeout);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
if (Url.IsLocalUrl(ReturnUrl)){
return Redirect(ReturnUrl);
}
else{
return RedirectToAction("Index", "Home");
}
}
else{
message = "Invalid Credential Provided";
}
}
else {
message = "Invalid Credential Provided";
}
}
ViewBag.Message = message;
return View();
}
Home Controller and index action where I redirect when I login,
This is Home Controller Where I redirected After Logging successfully please some one give a code for home controller and index action where i can Get Id of user That login and and and tell me how to show that in view
public class HomeController : Controller{
LoginEntities db = new LoginEntities();
// GET: Home
[Authorize]
public ActionResult Index(){
if (Session.Contents.Count == 0){
RedirectToAction("Login", "User");
}
return View();
}
}
Updated my code below, This might or might not work coz its coded here manually not on actual VS :P
// /Controller/TestController.cs
namespace XXXX.Controllers
{
public class TestController : Controller
{
public ActionResult User()
{
String UserId = User.Identity.GetUserId().ToString();
ApplicationDbContext db = new ApplicationDbContext();
var rs = db.Users.Find(UserId);
var model = new UserViewModel
{
UserName = rs.UserName,
FirstName = rs.FirstName,
LastName = rs.LastName,
Email = rs.Email
};
db.Dispose();
return View(model);
}
}
}
// /Models/UserViewModel.cs
namespace XXXX.Models
{
public class UserViewModel
{
public string Id { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
// /Views/Test/User.cshtml
#model XXXX.Models.UsersCreateViewModel
<p>
#Html.Raw(Model.FirstName)
</p>
above is just a sample you can use the info further

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'TagId'

Im new to MVC and I had this problem, please help me,
when I try to upload an image to my website project ,this error come up
"There is no ViewData item of type 'IEnumerable' that has the key 'TagId'."
this is my view model:
#model ImageSharingWithAuth.Models.ImageView
#{
ViewBag.Title = "Upload an Image";
}
<h2>#ViewBag.Title </h2>
#{Html.BeginForm("Upload", "Images", FormMethod.Post, new {enctype ="multipart/form-data"});}
<fieldset>
<legend >
Enter Image Information
</legend>
#Html.AntiForgeryToken()
<p>
Caption: #Html.TextBoxFor(model=>model.Caption)
#Html.ValidationMessage("Caption")
</p>
<p>
Select a tag : #Html.DropDownListFor(model=>model.TagId , ViewBag.Tags as SelectList)
</p>
<p>
Description :<br />
#Html.TextAreaFor(model=> model.Description,5,40,null)
#Html.ValidationMessage("Description")
</p>
<p>
Date taken: #Html.TextBoxFor(model=>model.DateTaken)
#Html.ValidationMessage("DateTaken")
</p>
<p>
<input type="file" name="ImageFile" />
</p>
<p>
<input type="submit" value="Upload" />
</p>
</fieldset>
<p>#ViewBag.Message</p>
<p> #Html.ValidationSummary() </p>
#{Html.EndForm(); }
this is the get and set for uploading:
private ImageSharingDB db = new ImageSharingDB();
[HttpGet]
public ActionResult Upload()
{
CheckAda();
//string userid = GetLoggedInUser();
//if (userid == null) {
// return ForceLogin();
//}
//else
{
ViewBag.Message = "";
//IEnumerable<Tag> tags = db.Tags;
ViewBag.Tags = new SelectList(db.Tags, "Id", "Name",1);
return View();
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(ImageView image, HttpPostedFileBase ImageFile)
{
CheckAda();
TryUpdateModel(image);
if (ModelState.IsValid)
{
String userid = GetLoggedInUser();
//if (userid != null)
//{
// return ForceLogin();
//}
//else
User user = db.Users.SingleOrDefault(u => u.Userid.Equals(userid));
if (user != null)
{
// save image info on the db
Image imageEntity = new Image();
imageEntity.Id = image.Id;
imageEntity.Caption = image.Caption;
imageEntity.Description = image.Description;
imageEntity.DateTaken = image.DateTaken;
imageEntity.Approved = false;
imageEntity.User = user;
imageEntity.TagId = image.TagId;
if (ImageFile != null && ImageFile.ContentLength > 0)
{
db.Images.Add(imageEntity);
db.SaveChanges();
String imgFileName = Server.MapPath("~/Content/Images/img-"+imageEntity.Id+".jpg");
ImageFile.SaveAs(imgFileName);
return View("Details", image);
//return RedirectToAction("Details", imageEntity.Id);
}
else
{
ViewBag.Message = "No such image file specified";
return View();
}
}
else
{
ViewBag.Message = "No Scuh userid registered";
return View();
}
}
else
{
ViewBag.Message = "Please crrect the errorsin the form!";
return View();
}
}
this the model for ImageView :
namespace ImageSharingWithAuth.Models
{
public class ImageView
{
[Required]
[StringLength(40)]
public String Caption { get; set; }
[Required]
public int TagId { get; set; }
[Required]
[StringLength(200)]
public String Description { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d}",ApplyFormatInEditMode=true)]
public DateTime DateTaken { get; set; }
[ScaffoldColumn(false)]
public int Id;
[ScaffoldColumn(false)]
public String Userid { get; set; }
[ScaffoldColumn(false)]
public String TagName { get; set; }
}
}
and the model for Image:
namespace ImageSharingWithAuth.Models
{
public class Image
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual int Id {get;set;}
[MaxLength(40)]
public virtual string Caption { get; set; }
[MaxLength(200)]
public virtual string Description { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d}")]
public virtual DateTime DateTaken { get; set; }
public virtual bool Approved { get; set; }
[ForeignKey("User")]
public virtual int UserId { get; set; }
public virtual User User { get; set; }
[ForeignKey("Tag")]
public virtual int TagId { get; set; }
public virtual Tag Tag { get; set; }
public Image() {
Approved = false;
}
}
}
try this in else block in httpPost method of controller
else
{
ViewBag.Message = "Please crrect the errorsin the form!";
ViewBag.Tags = new SelectList(db.Tags, "Id", "Name",1);
return View();
}

Retrieving Data Depending on the Username

I am doing Authentication depending on the username.So an unauthorized person can't see any methods which is working fine.
The problem is all of the users are able to each others data.
Person A shouldn't see the records of person B so that he/she can't edit another person's records.Does anyone know how I can write a lambda expression for that?
I have my Edit method pasted below:
// GET: /IcerikDB_/Edit/5
[Authorize(Roles = "Administrator")]
public ActionResult Edit(int id)
{
icerik icerik = db.icerik.Find(id);
ViewBag.Kategorid = new SelectList(db.Kategoriler, "Id", "Adi", icerik.Kategorid);
ViewBag.Userid = new SelectList(db.Users, "UserId", "UserName", icerik.Userid);
return View(icerik);
}
[HttpPost]
public ActionResult Edit(icerik icerik)
{
if (ModelState.IsValid)
{
if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
{
string userName = User.Identity.Name;
var user = db.Users.First(u => u.UserName == userName);
icerik.Userid = user.UserId;
db.Entry(icerik).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
ViewBag.Kategorid = new SelectList(db.Kategoriler, "Id", "Adi", icerik.Kategorid);
ViewBag.Userid = new SelectList(db.Users, "UserId", "UserName", icerik.Userid);
return View(icerik);
}
Here is the code for icerik.cs
namespace KategoriEditor.Icerik_DB
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class icerik
{
public int Id { get; set; }
public Nullable<int> Kategorid { get; set; }
public Nullable<System.Guid> Userid { get; set; }
[DataType(DataType.Date)]
public Nullable<System.DateTime> Baslangic { get; set; }
[DataType(DataType.Date)]
public Nullable<System.DateTime> Bitis { get; set; }
public string tamicerik { get; set; }
public string kisaicerik { get; set; }
public string resimlink { get; set; }
public virtual Kategoriler Kategoriler { get; set; }
public virtual Users Users { get; set; }
}
}
Try this:
public ActionResult Edit(int id)
{
// Get the currently logged in user.
string userName = User.Identity.Name;
var user = db.Users.First(u => u.UserName == userName);
// Determine whether the requested id is the same id as the currently logged in user.
icerik icerik = db.icerik.Find(id);
if (icerik.Userid.HasValue && icerik.Userid.Value == user.UserId)
{
ViewBag.Kategorid = new SelectList(db.Kategoriler, "Id", "Adi", icerik.Kategorid);
// You should not need this SelectList anymore.
//ViewBag.Userid = new SelectList(db.Users, "UserId", "UserName", icerik.Userid);
return View(icerik);
}
// This redirect the unauthorized user to the homepage. This can be any other page of course.
return RedirectToAction("Index", "Home");
}

Categories