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.
Related
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.
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!
Can I have 3 divs with lists from database on my page? I'm beginner in asp.net mvc and I don't know how to exactly do it... When I want make 1 list I do:
public ActionResult Favs()
{
var db = new MyDbContext();
List<books> lb = db.DbBooks.ToList();
return View(lb);
}
Then I right click -> make view and check option 'list'.
But what, if I want to see 3 diffrent lists?
public ActionResult Favs()
{
var db = new MyDbContext();
List<book> lb = db.DbBooks.ToList();
List<magazine> lm = db.DbMagazines.ToList();
List<author> la = db.DbAuthors.ToList();
return View(lb);
////////how return rest of them???
}
I will be thankful for any help!
You should use a Model class for your return View. (note this is all very rough code knocked up quickly)
Something like
public class MyListsModel
{
public List<book> Books { get; set; }
public List<magazine> Magazines { get; set; }
public List<author> Authorss { get; set; }
}
Then your ActionResult would be something like
var myModel = new MyListsModel();
myModel.Books = db.DbBooks.ToList();
myModel.Magazines = db.DbMagazines.ToList();
myModel.Author = db.DbAuthors.ToList();
return View(myModel);
You can then use those lists in your View page which might look similar to this:
#model MyListsModel
#{
ViewBag.Title = "My Page;
}
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
#foreach(book bookItem in Model.Books)
{
// Do something and repeat this type of action for each list
}
}
How to print the result of query in View page for ASP.NET MVC?
My code is:
public ActionResult Index()
{
var list = from m in db.MenuTables
select m.MenuName;
return View(list);
}
Now what should i write to print the result of this query in View Page?
Personally, I would get in the habit of having ViewModels and then strongly typing your View, to that model.
The model will expose ONLY THE DATA you want to display. Nothing more, nothing less. So let's assume you want to display the Name, Price and some other meta data.
Pseudo-code:
//View Model
public class MenuItem
{
public string Name { get; set; }
public decimal Price { get; set; }
public bool IsVegetarian { get; set; ]
}
public class IndexViewModel
{
public IList<MenuItem> MenuItems { get; set; }
public string MaybeSomeMessage { get; set; }
}
//in Controller
public ActionResult Index()
{
// This gets the menu items from your db, or cache or whatever.
var menuItemsFromDb = GetMenuItems();
// Let's start populating the view model.
IndexViewModel model = new IndexViewModel();
// Project the results to your model.
IList<MenuItems> menuItems = null;
if (menuItemsFromDb != null)
{
model.MenuItems = (from menuItem in menuItemsFromDb
select new MenuItem() {
Name = menuItem.Name,
Price = menuItem.Price,
IsVegetarian = menuItem.IsVegetarian
}).ToList();
}
// Anything else...
model.MaybeSomeMessage = "Hi There!";
return View(model);
}
//in View
#model IndexViewModel
<h3>#Model.MaybeSomeMessage</h3>
<ul>
#foreach(var item in Model.MenuItems)
{
<li>#item.Name - $ #item.Price</li>
}
</ul>
etc..
Note I've skipped some error checking, etc.
The point: only pass what you need.
At first, you may think this is much more code than is necessary. The best answer I can suggest to that thought, is that in the long run, you'll thank yourself for getting in the habit of this because the view should only ever know about the exact data it requires.
Nothing more, nothing less. Sending the least amount of data means you have a very light and simple view which will make your support/debugging much better. Next, you'll be able to unit test your controllers with a lot more intelligence and smarts, when you get to that.
Assuming that list is an IEnumerable of strings (i.e. that MenuName is a string).
In your view, accept the model IEnumerable<string>
#model IEnumerable<string>
and then enumerate it
#foreach( string s in Model )
{
<div>
#s
</div>
}
The first thing you want to do is call ToList() or else you could possibly be executing the same SQL query multiple times.
public ActionResult Index()
{
var list = (from m in db.MenuTables
select m.MenuName).ToList();
return View(list);
}
Secondly, I wouldn't just pass up a full list like that. You should create a ViewModel. That will allow you to pass up more data later on with a smaller effort.
public ActionResult Index()
{
var model = new IndexModel();
model.Tables = db.MenuTables.ToList();
model.AnotherValue = "MENUS";
return View(model);
}
Now we are on the view, you will need to set the model and iterate the table.
#model IndexModel
<h3>#Model.AnotherValue</h3>
<ul>
#foreach( var table in Model.Tables) {
<li>#table.Name<li>
}
</ul>
public ActionResult Index()
{
var list = from m in db.MenuTables
select m.MenuName;
return View(list);
}
//In View
#model IEnumerable<ProjectName.models.MenuTables>
#foreach(var item in Model)
{
#item.Field_Name
}
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>