I am creating mvc4 applicationn using entity framework 5
i am creating a page this contains checkboxes
i created table in db
model class
public class EmpSkillSet
{
public int ID { get; set; }
public string Skill { get; set; }
public bool isSelected { get; set; }
}
}
controller
[HttpPost]
public string AddSkills(IEnumerable<EmpSkillSet> skills)
{
}
How do I create a checkbox in the view?
Then how do i get its value from the database?
By using this example you can fetch only boolen value (True or False)
In view:
#Html.CheckBox("MonOpen", l.MonOpen)
In MOdel:
public class Shop
{
public bool MonOpen { get; set; }
....
}
in controller:
[HttpPost]
public ActionResult ShopCreate(Shop location)
{
Location newShop = new Location();
newShop.MonOpen = location.MonOpen;
....
}
Related
I am a newbie learning ASP.NET MVC from book.I am using NInject to Implement IoC. I have created a data model for Job and Location as below
Table Name - JobDetails
JobId<PK>
LocationId<FK>
JobName
Table Name - Location
LocationId<PK>
LocationName
I have created Entities for Location and JobDetails as Below
JobDetails
public class JobDetails
{
[Key]
public int JOBID { get; set; }
public int LocationID { get; set; }
public string JOBNAME { get; set; }
}
Location
public class Location
{
[Key]
public int LocationID{ get; set; }
public string LocationName { get; set; }
}
Also I have my Abstract and Context Class for Job Details and Location as below
public interface IJobDetails
{
IEnumerable<JobDetails> jobDetailsInterface { get; }
}
public interface ILocation
{
IEnumerable<Location> locationInterface { get; }
}
public class EFLocationRepository : ILocation
{
public EFDbContext context = new EFDbContext();
public IEnumerable<Location> locationInterface
{
get { return context.Location; }
}
}
public class EFJobRepository : IJobDetails
{
public EFDbContext context = new EFDbContext();
public IEnumerable<JobDetails> jobDetailsInterface
{
get { return context.JobDetails; }
}
}
My Model class for Job and Location are as below
public class JobListViewModel
{
public IEnumerable<JobDetails> jobDetails { get; set; }
}
public class LocationListViewModel
{
public IEnumerable<Location> Location { get; set; }
}
In my JobDetail Controller I want to display the location name instead of Location Id.
My JobDetail controller is as below
public class JobController : Controller
{
public IJobDetails repository;
public JobController(IJobDetails job)
{
repository = job;
}
public ViewResult List()
{
return View(repository.jobDetailsInterface);
}
}
How to display Location Name instead of Location id in my Job View?
N.B-I am learning MVC from Adam Freeman book and trying to create something new.Please let me know what I have done is correct or not.
Adding to sleeyuen's response. You may want to add a "navigation" property to JobDetails model, like below:
public class JobDetails
{
[Key]
public int JOBID { get; set; }
public int LocationID { get; set; }
public string JOBNAME { get; set; }
public virtual Location JobLocation { get; set; }
}
Then you should be able to access Location name from view by doing: repository.jobDetailsInterface.JobLocation.LocationName
In your scenario I believe entity framework will be able to infer relationships from the model structure, so you won't need entity configuration set up
Please note, this approach leads to N+1
Hope this helps :)
I Have two simple model Model1, Model2 as below:
public class Model1
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
public class Model2
{
public int Id { get; set; }
[Required]
public string Code { get; set; }
}
I Have a BigModel contains two other model as:
public class BigModel
{
public BigModel()
{
Model1 = new Model1 ();
Model2 = new Model2();
}
public Model1 Model1 { get; set; }
public Model2 Model2 { get; set; }
}
and in my Controller:
public ActionResult Register(BigModel bigModel)
{
if (ModelState.IsValid)
{
//do somthing
return RedirectToAction("Index");
}
return View(bigModel);
}
my question is Why ModelState.IsValid is always true? though data annotations are set. and How can I validate two models in one action?
Please don't use above way.Always try to use ViewModel with your views.Put all your data annotations on that ViewModel and check that inside the action method.
Plese check below mentioned sample ViewModel as an example.
public class ProductViewModel
{
public Guid Id { get; set; }
[Required(ErrorMessage = "required")]
public string ProductName { get; set; }
public int SelectedValue { get; set; }
public virtual ProductCategory ProductCategory { get; set; }
[DisplayName("Product Category")]
public virtual ICollection<ProductCategory> ProductCategories { get; set; }
}
Inside the Action Method:
[HttpPost]
public ActionResult AddProduct(ProductViewModel productViewModel) //save entered data
{
//get product category for selected drop down list value
var prodcutCategory = Repository.GetProductCategory(productViewModel.SelectedValue);
//for get all product categories
var prodcutCategories = Repository.GetAllProductCategories();
//for fill the drop down list when validation fails
productViewModel.ProductCategories = prodcutCategories;
//for initialize Product domain model
var productObj = new Product
{
ProductName = productViewModel.ProductName,
ProductCategory = prodcutCategory,
};
if (ModelState.IsValid) //check for any validation errors
{
//save recived data into database
Repository.AddProduct(productObj);
return RedirectToAction("AddProduct");
}
else
{
//when validation failed return viewmodel back to UI (View)
return View(productViewModel);
}
}
I want get some qualification about reloading model in mvc action. For example:
I have some class model:
public class PresentationItemModel()
{
public int Id { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public string Type { get; set; }
public List<int> PresentationIdList { get; set; }
}
And some controller action:
public ActionResult PostAction(PresentationItemModel model)
{
...
if(model.PresentationIdList == null)
{
model.PresentationIdList = new List<int>();
}
model.PresentationIdList.Add(model.Id);
...
...
...
}
I can call PostAction method several times and I want to save model.PresentationIdList result with all id's. But every time my PresentationIdList reloading with all model. But it's standard behavior.
Can I resolve it?
All you need to do is return the model object from your PostAction:
public ActionResult PostAction(PresentationItemModel model)
{
...
if(model.PresentationIdList == null)
{
model.PresentationIdList = new List<int>();
}
model.PresentationIdList.Add(model.Id);
...
...
...
return new ActionResult(model);
}
I am just getting into MVC 4 and Entity Framework 5 and want to know if what I am doing is correct?
I have a UserObject and a JobObject, the jobObject has a reference to a User Object.
public class Job
{
public int id { get; set; }
public virtual MyUser User { get; set; }
public JobType JobType { get; set; }
}
When I want to create an instance of the Job I am passing in the query string a parameter UserID, but the Job only deals with an instance of MyUser.
Is the following the correct way to associate the user to the job?
[HttpPost]
public ActionResult Create(Job job, int userid)
{
if (ModelState.IsValid)
{
MyUser staffmember = db.MyUsers.Find(userid);
if (staffmember == null)
{
return View("StaffMemberNotFound");
}
job.User = staffmember;
db.Jobs.Add(job);
db.SaveChanges();
}
}
Or is there a better way to associate the user to the job?
Your way will work but I prefer to simply work with ids if possible.
What I would suggest is that you add a MyUserId property to your Job class (remember to update the database if you are using codefirst):
public class Job
{
public int id { get; set; }
[ForeignKey("User")]
public int MyUserId { get; set: }
public virtual MyUser User { get; set; }
public JobType JobType { get; set; }
}
Then simply populate the MyUserId. You can also change your check to simply check if the id exists as apposed to finding an object and letting EF map that to a class before returning it to you
[HttpPost]
public ActionResult Create(Job job, int userid)
{
if (ModelState.IsValid)
{
if (!db.MyUsers.Any(u => u.Id == userid)
{
return View("StaffMemberNotFound");
}
job.MyUserId = userid;
db.Jobs.Add(job);
db.SaveChanges();
}
}
EF will do the rest of the mapping for you when you next retrieve the record from the database.
Your approach works fine, the only small optmization you could make is not taking the "retrieval hit" of MyUser staffmember = db.MyUsers.Find(userid); since you already have the userid.
I am using ASP.NET MVC 4 and Entity Framework 5.0, and here is my code (different model objects, but same intent as what you are doing).
Note: I let EF generate my model classes by right-clicking on the Models folder and choosing Add->ADO.NET Entity Data Model in VS.NET 2012.
Store.Models.Product
namespace Store.Models
{
using System;
using System.Collections.Generic;
public partial class Product
{
public long Id { get; set; }
public string ProductName { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
public System.DateTime DateAdded { get; set; }
public Nullable<long> CategoryId { get; set; }
public virtual Category Category { get; set; }
}
}
Store.Models.Category
namespace Store.Models
{
using System;
using System.Collections.Generic;
public partial class Category
{
public Category()
{
this.Products = new HashSet<Product>();
}
public long Id { get; set; }
public string CategoryName { get; set; }
public System.DateTime DateAdded { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
}
On my Create.cshtml page, I have the User select the CategoryId from the drop-down list. This Category Id is bound to Product.CategoryId. All I do in my method is this:
ProductController
public class ProductController : Controller
{
...
[HttpPost]
public ActionResult Create(Product product)
{
product.DateAdded = DateTime.Now;
if (dbContext != null)
{
dbContext.Products.Add(product);
dbContext.SaveChanges();
}
return RedirectToAction("Index");
}
...
}
I am new to ASP.NET MVC. I need to build a composite viewmodel out of three nested or cascading classes: Sport>Tournament>TournamentEvent
public class Sport
{
public int Id { get; set; }
public string SportName { get; set; }
public virtual ICollection<Tournament> Tournaments { get; set; }
}
public class Tournament
{
public int Id { get; set; }
public string TournamentName { get; set; }
public int SportId { get; set; }
public virtual ICollection<TournamentEvent> TournamentEvents { get; set; }
}
public class TournamentEvent
{
public int Id { get; set; }
public string EventName { get; set; }
public int TournamentId { get; set; }
}
As you can gather, each sport contains a collection of tournaments and each tournament contains a collection of events. I need to construct an unordered list, like so:
<li> Soccer
<li>English Premier League
<li>Chelsea v Arsenal</li>
</li>
</li>
I need to build a composite viewmodel, using linq, to pass to my view, but I just can't figure it out. Please help
Don't you just need a parent vie model that contains a list of Sport?
public class Sport
{
public List<Sport> Sports { get; set; }
}
You can iterate through the collections using razor.
Can you clarify where you think linq comes into it? I might have got the wrong end of the stick.
I don't think that works, tom. I need access to the Tournament and TournamentEvent classes and I need to load them into my object, which is where linq comes in. In the SportsController:
public partial class SportsController : Controller
{
private MyDb db = new MyDb();
public virtual ActionResult Index()
{
var menuObject = from s in db.Sports
select s;
return View(menuObject);
}
}
Create a class call it SportTournamentEventViewModel.cs
using "LibraryName".Models;
public class SportTournamentEventViewModel
{
public List<Sport> Sports {get;set;}
public List<Tournament> Tournaments {get;set;}
public List<TournamentEvent> Events {get;set;}
}
in your action
private NameOfEntities db = new NameOfEntities();
public ActionResult "ActionResultName"()
{
db.Configuration.LazyLoading = false;
var sportList = db.Sport.ToList();
var tournamentList = db.Tournament.ToList();
var eventList = db.TournamentEvents.ToList();
var viewModel = new SportTournamentViewModel
{
Sports = sportList,
Tournaments = tournamentList,
Events = eventList,
};
return View(viewModel);
}