Change enum value in Database using EF - asp.net

sorry for my english, hope you're doing okay , i'm stuck in a list situation using MVC, i have a class named student
public class student
{
[Key]
public int student_Id { get; set; }
public DateTime startdate { get; set; }
public DateTime enddate { get; set; }
public statut studentstatut { get; set; }
}
public enum statut
{
Garden,
Elementary,
College,
}
i want to edit the class student , i can edit the Id , both dates , but when i want to edit the enum statut it won't , it stays in Garden and when i check my database in studentstatut it shows 0, i don't know how to make them dynamic so that i can see the studentstatut in the database and edit the statut (for exemple edited from garden to elementary ) , can anyone help please ?
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Alimentation(Student Student)
{
if (ModelState.IsValid)
{
db.Orders.Add(Student);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(Student);
}
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Student student= db.Students.Find(id);
if (order == null)
{
return HttpNotFound();
}
return View(student);
}
////POST: /Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Student_id,startdate,enddate,AtmAmount,Statut")] Student student)
{
if (ModelState.IsValid)
{
db.Entry(student).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("index");
}
return View(student);
}

First, I would verify that you are getting the correct data back from your HttpPost Edit method. If you're able to edit and save the other fields It's possible that your client-side control is not correctly setting the correct field for your student object. Put a breakpoing in that method to verify that the studentstatut field is correctly being set.
If it is, and it is somehow not saving to your database context, you can try manually setting the field rather than using EntityState.Modified. You can do that with something along the lines of:
db.Entry(student).studentstatut = student.stdentstatut;
Though usually EntityState.Modified should do the trick.

Related

Returning a list opens a blank page with requested values

In my controller I have a function to get the roles that belong to a user.
This function is using .GetRolesAsync() and is returning an IList.
In the browser the user can submit a name, and see the roles for a user.
This however returns my list in a blank page. example
Controller :
[HttpPost]
public async Task<IList<string>> GetRoles(UserRoleViewModel model)
{
ApplicationUser user = await _userManager.FindByEmailAsync(model.Email);
if(user != null)
{
model.GetRoles = await _userManager.GetRolesAsync(user);
}
return model.GetRoles;
}
How can I return this list to my ViewModel without opening a blank page so I can call this from my view ?
ViewModel :
public class UserRoleViewModel
{
public List<SelectListItem> Roles { get; set; }
public IList<string> GetRoles { get; set; }
public string Role { get; set;}
public string Email { get; set; }
public string CurrentPassword { get; set; }
public string NewPassword { get; set; }
}
As per my knowledge, you are getting the blank page because , when the below method get executes,
Existing code :
[HttpPost]
public async Task<IList<string>> GetRoles(UserRoleViewModel model)
{
ApplicationUser user = await _userManager.FindByEmailAsync(model.Email);
if(user != null)
{
model.GetRoles = await _userManager.GetRolesAsync(user);
}
return model.GetRoles;
}
It return just result of list and doesn't return any actionresult to retain in the same view
Solution :
Make the returntype of the method like below
Replaced code :
[HttpPost]
public async Task<ActionResult> GetRoles(UserRoleViewModel model)
{
ApplicationUser user = await _userManager.FindByEmailAsync(model.Email);
if(user != null)
{
model.GetRoles = await _userManager.GetRolesAsync(user);
}
return view("viewname")
//Note: here viewname can be the same view ,where this post method was
// called if you dont want to create new view
}
And specify the view name of which you called this post method, if you dont want to create a new view.
So that it wont give a blank page for the user , when it is called.
Hope the above information was useful , kindly let me know your thoughts or feedbacks
Thanks
Karthik

How to Update a database column after changes from front end ASP.NET Mvc? Create a CheckBox and make it READONLY?

I have created an application for several stores to fill in a questionnaire, the application has several tables within the database. Two of them are the ones I am focusing on which are Audit and Storequestions. The Audit table contains the data for the stores for example: storename, and its primary key is “AuditId”. The storesquestion table contains all the questionnaire table and AuditId as a foreign key form the Audit table.
I am wanting to create a Read Only tick box as an indication in order to find out which stores has completed the questionnaire as the only way I know which has completed the questionnaire is by looking in the database. My approach to re4solve this matter was to create a new column called read only within the Audit table with a Boolean datatype so when a store has completed the questionnaire it will set the read only row to 1(true).
Could do with a bit of Help as I don’t seem to go forward at the moment
Thanks in advance
public ActionResult Create()
{
StoreQuestions sq = new StoreQuestions();
sq.AuditId = (int)System.Web.HttpContext.Current.Session["AuditId"];
return View(sq);
}
//
// POST: /StoreQuestions/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(StoreQuestions storequestions)
{
if (ModelState.IsValid)
{
db.StoreQuestions.Add(storequestions);
db.SaveChanges();
return RedirectToAction("Details", "Audit", new { id = storequestions.AuditId });
}
return View(storequestions);
}
ViewModel
public class MainModel
{
public StoreAudit StoreAudit { get; set; }
public StoreQuestions StoreQuestion { get; set; }
public List<StoreAudit> StoreAuditList { get; set; }
public List<StoreQuestions> StoreQuestionsList { get; set; }
public List<User> User { get; set; }
public List<string> StoreWindow { get; set; }
}
}
Okay I think I understand what you're trying to do. In order to update the readonly property to true you have to find the audit record and then change the value of that record's readonly property.
Like so:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(StoreQuestions storequestions)
{
if (ModelState.IsValid)
{
Audit findingAudit = db.AuditTable.Find(storequestions.AuditId);
// db being your connectionstring property
findingAudit.readonly = true;
db.StoreQuestions.Add(storequestions);
db.SaveChanges();
return RedirectToAction("Details", "Audit", new { id = storequestions.AuditId });
}
return View(storequestions);
}
I hope this helps!

How to add the UserId to posted data by Logged User in ASP.NET MVC 4

So what I'm doing might seem simple, but I don't know exactly how to do it.
I have already registered and logged in with an account (I'm using the default membership system used in ASP.NET MVC 4) and so I want to do add my UserId to some data I'm inserting to the database.
This is the model of the data I'm inserting:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Reroute.Models
{
public class Request
{
public int RequestId { get; set; }
// I want to add UserId based on my current session
public int UserId { get; set; }
public string OrderNumber { get; set; }
public string TrackingNumber { get; set; }
public string CurrentAddress { get; set; }
public string NewAddress { get; set; }
public string Comment { get; set; }
}
}
And the ActionResult (here's where I supposed I have to make the changes):
[HttpPost]
public ActionResult Create(Request collection)
{
try
{
_db.Requests.Add(collection);
_db.SaveChanges();
//return RedirectToAction("Index");
return Content("Done! Added to DB");
}
catch
{
return View();
}
}
Thanks
use this it gets u the userid ...
Membership.GetUser().ProviderUserKey
You can save the UserId of the authenticated user in Session after logging in:
Session["UserId"] = userId;
or since you are using FormsAuthentication you can either use the UserData property as shown here or do a nice-that-will-do-trick:
public SignInUser(string name, string id) {
// store the userid
FormsAuthentication.SetAuthCookie(name + '|' + id, false);
}
then retrieve the Name and UserId like this:
public int CurrentUserId
{
get
{
var context = HttpContext.Current;
if (context == null) return 0;
return context.Request.IsAuthenticated
? Convert.ToInt32(context.User.Identity.Name.Split('|')[1])
: 0;
}
}
public string CurrentUserName
{
get
{
var context = HttpContext.Current;
if (context == null) return string.Empty;
return context.Request.IsAuthenticated
? context.User.Identity.Name.Split('|')[0]
: string.Empty;
}
}
You can have those method and properties in a class so you have them in one place, I actually do it that way. Now, you can call it in your controller like so:
[HttpPost]
public ActionResult Create(Request collection)
{
try
{
collection.UserId = _authProvider.CurrentUserId;
// if you want to use session, I prefer the FormsAuthentication approach
// you need to do additional check that the Session has not expired (not null)
collection.UserId = Session["UserId"];
_db.Requests.Add(collection);
_db.SaveChanges();
//return RedirectToAction("Index");
return Content("Done! Added to DB");
}
catch
{
return View();
}
}
_authProvider is an instance of the class that has the code I gave above.
This should work.
var loggedInUserName=Thread.CurrentPrincipal.Identity.Name;
var user=Membership.GetUser(loggedInUserName);
var key = user.ProviderUserKey;
T
Assuming your Create also has a GET which is loaded up and used as the model for Create.cshtml, you would just need to set it explicitly in that ActionResult
public ActionResult Create()
{
Result model = new Result();
model.UserId = myUserId;
}
Then in your Create.cshtml you could have a hidden field for it:
#Html.HiddenFor(m => m.UserId)
I would still check in the POST to make sure the user doing the saving is allowed to be saving and hasn't spoofed your hidden field value to somebody completely different.

How to edit using ViewData model

I have created a View Model based on combination of three Tables.
I click on Edit action it displays the Data from Three tables correctly.
But when i click on Save button i am not able to get data either from FormCollection or from Request["Id"]
Please suggest it the possible way.
public class ConferenceResourceEditModel
{
public ConferenceRoom ConferenceRoom { get; set; }
public Resources Resources { get; set; }
public ResourceAllocation ResourceAllocation { get; set; }
}
public ActionResult Edit(int id)
{
//ConferenceRoom conferenceroom = db.ConferenceRooms.Find(id);
var query =
from c in db.ConferenceRooms
from r in db.Resourcess
from ra in db.ResourceAllocation
where c.ConferenceID == id
where c.ConferenceID == ra.ConferenceID
where r.ResourceID ==ra.ResourceID
select new ConferenceResourceEditModel { ConferenceRoom = c, Resources = r,ResourceAllocation=ra };
return View(query);
}
//
// POST: /ConferenceRoom/Edit/5
[HttpPost]
public ActionResult Edit(FormCollection form, int id, ConferenceResourceEditModel conferenceroom,ConferenceRoom crf)
{
if (ModelState.IsValid)
{
db.Entry(conferenceroom).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(conferenceroom);
}
Look up model binding on the http://www.asp.net/mvc site where there are magnificent tutorials about this kind of thing.
in a nutshell your controller action will take a parameter of type YOURVIEWMODEL and bind to it automatically
Use some ORM ( like EntityFramework,personally i recommend DatabaseFirst approach). Using something like that:
var query =
from c in db.ConferenceRooms
from r in db.Resourcess
from ra in db.ResourceAllocation
where c.ConferenceID == id
where c.ConferenceID == ra.ConferenceID
where r.ResourceID ==ra.ResourceID
is much more complicated and difficult. Hope it will help.

How to make simple calculations using model items and an input from a form in ASP.net MVC 3?

Am new to programming and ASP.net MVC 3 so don't be surprised by my lack of knowledge on this.. Okay, I want to multiply two decimals, One decimal comes from the form that a user fills and the other decimal comes from the Model class (gets it from the database).
I have two Model classes called RATE & PROJECTMATERIAL . The RATE class has an item called Amount that states the amount of a Rate and the PROJECTMATERIAL class has an item quantity. The classes are related and i want to be able to say variable1 = quantity*Rates.amount and return variable1 to the my Index, Delete, Details views. I don't want to store variable1 to my database but i just want to display in my views.....but i don't know how and where to do it
Code from Project material class..
public class ProjectMaterial
{
public int ProjectMaterialID { get; set; }
[Required]
[Display(Name = "Scope Name")]
public int? ScopeID { get; set; }
[Required]
[Display(Name = "Rate Code")]
public int? RateID { get; set; }
[Required]
[Display(Name = "Quantity")]
public decimal Quantity { get; set; }
public virtual Scope Scopes { get; set; }
public virtual Rate Rates { get; set; }
}
Code from scope class..
public class Rate
{
public int RateID { get; set; }
[Required]
[Display(Name = "Rate Code")]
public int RateCode { get; set; }
[Required]
[Display(Name = "Unit")]
public string Unit { get; set; }
[Required]
[Display(Name = "Description")]
public string Description { get; set; }
[Required]
[Display(Name = "Amount")]
public decimal Amount { get; set; }
public virtual ICollection<ProjectMaterial> ProjectMaterials { get; set; }
}
Code from project controller class...
public class ProjectMaterialController : Controller
{
private ContructorContext db = new ContructorContext();
//
// GET: /ProjectMaterial/
public ViewResult Index()
{
var projectmaterials = db.ProjectMaterials.Include(p => p.Scopes).Include(p => p.Rates);
return View(projectmaterials.ToList());
}
//
// GET: /ProjectMaterial/Details/5
public ViewResult Details(int id)
{
ProjectMaterial projectmaterial = db.ProjectMaterials.Find(id);
return View(projectmaterial);
}
//
// GET: /ProjectMaterial/Create
public ActionResult Create()
{
ViewBag.ScopeID = new SelectList(db.Scopes, "ScopeID", "ScopeName");
ViewBag.RateID = new SelectList(db.Rates, "RateID", "Unit");
return View();
}
//
// POST: /ProjectMaterial/Create
[HttpPost]
public ActionResult Create(ProjectMaterial projectmaterial)
{
if (ModelState.IsValid)
{
db.ProjectMaterials.Add(projectmaterial);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ScopeID = new SelectList(db.Scopes, "ScopeID", "ScopeName", projectmaterial.ScopeID);
ViewBag.RateID = new SelectList(db.Rates, "RateID", "Unit", projectmaterial.RateID);
return View(projectmaterial);
}
//
// GET: /ProjectMaterial/Edit/5
public ActionResult Edit(int id)
{
ProjectMaterial projectmaterial = db.ProjectMaterials.Find(id);
ViewBag.ScopeID = new SelectList(db.Scopes, "ScopeID", "ScopeName", projectmaterial.ScopeID);
ViewBag.RateID = new SelectList(db.Rates, "RateID", "Unit", projectmaterial.RateID);
return View(projectmaterial);
}
//
// POST: /ProjectMaterial/Edit/5
[HttpPost]
public ActionResult Edit(ProjectMaterial projectmaterial)
{
if (ModelState.IsValid)
{
db.Entry(projectmaterial).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ScopeID = new SelectList(db.Scopes, "ScopeID", "ScopeName", projectmaterial.ScopeID);
ViewBag.RateID = new SelectList(db.Rates, "RateID", "Unit", projectmaterial.RateID);
return View(projectmaterial);
}
//
// GET: /ProjectMaterial/Delete/5
public ActionResult Delete(int id)
{
ProjectMaterial projectmaterial = db.ProjectMaterials.Find(id);
return View(projectmaterial);
}
//
// POST: /ProjectMaterial/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
ProjectMaterial projectmaterial = db.ProjectMaterials.Find(id);
db.ProjectMaterials.Remove(projectmaterial);
db.SaveChanges();
return RedirectToAction("Index");
}
Thanx in advance guys!! really need your help.
Seeing as you say you're new to MVC, I've given you a few options and explained which is best and why, because it's better to understand now so you don't get in to bad habits, especially if you start building larger projects.
You don't necessarily need to create a variable, because you can do that calculation in your view. Because you are passing the domain model directly to the view you can do (in razor):
#(Model.Quantity * Model.Rates.Amount)
Although this is the easiest option I wouldn't necessarily recommend this as views should be dumb - see ASP.NET MVC: How dumb should my view be?.
Another option is to do the calculation in the controller and pass the value in the ViewBag, e.g.:
public ViewResult Details(int id)
{
ProjectMaterial projectmaterial = db.ProjectMaterials.Find(id);
ViewBag.Price = projectmaterial.Quantity * projectmaterial.Rates.Amountl
return View(projectmaterial);
}
Then you could use it in your view like:
#ViewBag.Price
Again, this is easy but I wouldn't recommend it, as ViewBag isn't strongly typed - see Is using ViewBag in MVC bad?.
You could put a property on your ProjectMaterial class like, which is a neat solution.
public decimal Price
{
get
{
return Quantity * Rates.Amount;
}
}
However, if Price is a property that is only ever used within your views (ie you just display it) then it probably shouldn't be in your domain model, as your domain model is just that - storing and accessing the raw data.
Maybe the best way is to create a viewmodel specific to your view (see http://stephenwalther.com/blog/archive/2009/04/13/asp.net-mvc-tip-50-ndash-create-view-models.aspx) with a Price propert. This means that the property is only used where it is needed, the domain model remains just that, your view remains dumb and your domain model is not exposed to your view. See Why Two Classes, View Model and Domain Model? also for a good explanation of view models
You could add a property to your ProjectMaterial model:
public decimal Price
{
get
{
return Quantity * Rates.Amount;
}
}
You might want to have a model function with instances of your self.rate, and self.material items passed on from your views. Or otherwise you can individually calculate the values of the multiplication in each view.
Either way, you should be able to store the copy over the value of multiplication (variable1) in the view's bag, and pass it onto each view without having to save it in the DB.
ViewBag.variable1 = rate*material
return View()
#(int.Parse(variable) * your value)
Additional to all the answers you can use Data Format String in model class, and Html Helper in View to maintain formatting in displayed results for numeric types, by modifying returned attribute in the Controller.
The purpose of applying the formatting in the model class, and the value transformation in the controller and keeping the view standard, is to achieve separation of concerns (SoC) for easier maintenance, and control over the code.
Consider this example:
Products Class Property
[Display(Name = "Max Disc %")]
[DisplayFormat(DataFormatString = "{0:P1}", ApplyFormatInEditMode = true)]
public decimal MaxDiscountRate { get; set; }
Products Controller
[HttpGet]
public ActionResult Details(int id)
{
if (id == 0)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Products products = _uow.Products.GetById(id);
if (products == null)
{
return HttpNotFound();
}
else
{
products.MaxDiscountRate /= 100;
}
return View(products);
}
Products Details View
<div class="detail">
<h5 class="text-teal">#Html.DisplayNameFor(model => model.MaxDiscountRate)</h5>
<span class="text-peru">#Html.DisplayFor(model => model.MaxDiscountRate)</span>
</div>

Resources