At first I should say i am compeletely newbie in MVC.
I have 3 Objects
public partial class Magazine
{
public Magazine()
{
this.NumberTitles = new HashSet<NumberTitle>();
}
public int Id { get; set; }
public int MagYear { get; set; }
public int MagNo { get; set; }
public int MagSeason { get; set; }
public string MagYear2 { get; set; }
public virtual ICollection<NumberTitle> NumberTitles { get; set; }
}
public partial class NumberTitle
{
public NumberTitle()
{
this.Articles = new HashSet<Article>();
}
public int Id { get; set; }
public int MagazineId { get; set; }
public int TitleId { get; set; }
public int position { get; set; }
public virtual ICollection<Article> Articles { get; set; }
public virtual Magazine Magazine { get; set; }
public virtual Title Title { get; set; }
}
public partial class Title
{
public Title()
{
this.ChildrenTitle = new HashSet<Title>();
this.NumberTitles = new HashSet<NumberTitle>();
}
public int Id { get; set; }
public string TitleText { get; set; }
public Nullable<int> ParentId { get; set; }
public virtual ICollection<Title> ChildrenTitle { get; set; }
public virtual Title ParentTitle { get; set; }
public virtual ICollection<NumberTitle> NumberTitles { get; set; }
}
In a View I want to have TextBox to show Magazine Number and 2 List boxes. one shows all the Available Titles and the Other just selected Titles for that Magazine Number.So I have made View Model
public class NumberTitleViewModel
{
public Magazine Magazine { get; set; }
public List<NumberTitle> NumberTitles { get; set; }
}
this is in controller. how can i get the list of titles for specified MagazineId
public ActionResult EditTitle(int id)
{
Func<IQueryable<Magazine>, IOrderedQueryable<Magazine>> orderByFunc = null;
Expression<Func<Magazine, bool>> filterExpr = null;
if (id>0)
{
filterExpr = p => p.Id.Equals(id);
}
Magazine magazine = unitOfWork.MagazineRepository.Get(filter: filterExpr, orderBy: orderByFunc, includeProperties: "").SingleOrDefault();
NumberTitleViewModel numberTitleViewMode = new NumberTitleViewModel();
numberTitleViewMode.Magazine = magazine;
Expression<Func<NumberTitle, bool>> filterExpr2 = null;
if (id > 0)
{
filterExpr2 = p => p.MagazineId.Equals(id);
}
var numberTitles = unitOfWork.NumberTitleRepository.Get(filterExpr2, null, includeProperties: "Title").ToList();
var titles = unitOfWork.TitleRepository.Get(null, null, "");
numberTitleViewMode.NumberTitles = numberTitles; ///this part doesn't show the Titles. how should access the TitleName not Id
ViewBag.titles = new SelectList(titles, "Id", "TitleText");
return View("../Panel/Magazine/EditTitle", "_BasicLayout", numberTitleViewMode);
}
Not sure what you have in your view but you should have something like:
#using NameSpace.Models
#model NameSpace.Models.NumberTitleViewModel
Then you can do something like this in your view:
foreach (NumberTitles item in #Model)
{
<label>#item.Title.TitleText</label>
}
Not exact but should get you close to what you need
Related
MODEL
namespace CG.MyPollSurveyAdmin.Models
{
public class CompletePollSurvey
{
public long PollSurveyID { get; set; }
public string Name { get; set; }
public List<OptionData> Options { get; set; }
public List<QuestionData> QuestionDetails { get; set; }
}
public class QuestionData
{
public string QuestionName { get; set; }
public long QuestionID { get; set; }
public int OptionID { get; set; }
public string OptionType { get; set; }
public string Option_1 { get; set; }
public string Option_2 { get; set; }
public string Option_3 { get; set; }
public string Option_4 { get; set; }
public string Option_5 { get; set; }
}
}
CONTROLLER
private List<Question> GetQuestionsById(long PollSurveyId)
{
MemoryStream outMemoryStream = RESTFulServiceHelper.Instance.ExecuteGetMethod(Constants.Method_GetAllQuestions, Convert.ToString(Session[Constants.NTLoginID]));
DataContractJsonSerializer outDataContractJsonSerialize = new DataContractJsonSerializer(typeof(List<Question>));
List<Question> lstQuestions = outDataContractJsonSerialize.ReadObject(outMemoryStream) as List<Question>;
List<Question> question = lstQuestions.Where(p => p.PollSurveyID == PollSurveyId).ToList();
return question;
}
public ActionResult Help(long PollSurveyID=2)
{
if (Session[Constants.Session_IsAdmin] != null && Convert.ToBoolean(Session[Constants.Session_IsAdmin]))
{
CompletePollSurvey completePollSurvey = new CompletePollSurvey();
List<Question> question = GetQuestionsById(Convert.ToInt64(PollSurveyID));
return View(completePollSurvey);
}
else
{
return RedirectToAction("Login");
}
}
Here is the model and controller of my program. Till now I'm getting All the questions for poll id=2 but I'm having difficulty in retrieving element from Question List and assign it to Model List elements(or list to list assignment).
For e.g I have 5 questions for Poll=2 and in each question there are 5 options
Model
public class Cart
{
public int id { get; set; }
public int userId { get; set; }
public int messageId { get; set; }
public virtual List<Product> cart { get; set; }
}
ViewModel
public class cartVM
{
public int id { get; set; }
public int productId { get; set; }
public int userId { get; set; }
public int messageId { get; set; }
public DateTime AddDate { get; set; }
public virtual List<Product> Product{ get; set; }
public List<int> SelectedProductIds { get; set; }
public IEnumerable<SelectListItem> CartChoices { get; set; }
}
Controller function to populate Selectedlist
/// here i can only display productname column, how can i display multiple columns for selectlistitem
private void CartChoices(cartVM model)
{
model.CartChoices = db.Products.Select(m => new SelectListItem
{
Value = ((int)m.ProductId).ToString(),
Text = m.productName
});
}
Razor View to display listbox
<div>
#Html.ListBoxFor(m => m.SelectedProductIds , Model.CartChoices)
</div>
Im using MVC 5 and EF 6.
There are 3 tables in my code: "Leads", "Phones", "LeadStatus" and a junction table "LeadPhones".
I want to show following properties in Index View:
Leads.FullName
LeadStatus.Status
Phones.PhoneID
How should I configure the LeadController?
public partial class Leads
{
public Leads()
{
this.LeadPhones = new HashSet<LeadPhones>();
}
[Key]
public int LeadID { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName { get { return NamePrefix + " " + FirstName + " " + LastName; } }
public int LeadStatusID { get; set; }
public virtual LeadStatus LeadStatus { get; set; }
public virtual ICollection<LeadPhones> LeadPhones { get; set; }
}
and
public partial class Phones
{
public Phones()
{
this.AccountPhones = new HashSet<AccountPhones>();
this.ContactPhones = new HashSet<ContactPhones>();
this.EmployeePhones = new HashSet<EmployeePhones>();
this.LeadPhones = new HashSet<LeadPhones>();
}
[Key]
public int PhoneID { get; set; }
public string PhoneNo { get; set; }
public virtual ICollection<LeadPhones> LeadPhones { get; set; }
}
and
public partial class LeadPhones
{
[Key]
public int LeadPhoneID { get; set; }
public int LeadID { get; set; }
public int PhoneID { get; set; }
public virtual Leads Leads { get; set; }
public virtual Phones Phones { get; set; }
}
and
public partial class LeadStatus
{
public LeadStatus()
{
this.Leads = new HashSet<Leads>();
}
[Key]
public int LeadStatusID { get; set; }
public string Status { get; set; }
public virtual ICollection<Leads> Leads { get; set; }
}
the following does not work:
public ActionResult Index()
{
var leads = db.Leads.Include(l => l.LeadStatus).Include(l => l.LeadPhones);
return View(leads);
}
The main problem is the "PhoneNo". How could I get that from a junction table?
Remove the LeadPhoneID column from the LeadPhones table -- It isn't necessary and will only cause problems for you. Remove all references to LeadPhones in your classes. Leads a virtual property to Phones (not LeadPhones). LeadPhones has a virtual property to Leads (not LeadPhones).
After you do that, then you should be able to:
var leads = db.Leads.Include(l => l.LeadStatus).Include(l => l.Phones);
public partial class Lead
{
public Lead()
{
this.Phones = new HashSet<Phone>();
}
[Key]
public int LeadID { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName { get { return NamePrefix + " " + FirstName + " " + LastName; } }
public int LeadStatusID { get; set; }
public virtual LeadStatus LeadStatus { get; set; }
public virtual ICollection<Phone> Phones { get; set; }
}
public partial class Phone
{
public Phone()
{
this.AccountPhones = new HashSet<AccountPhones>();
this.ContactPhones = new HashSet<ContactPhones>();
this.EmployeePhones = new HashSet<EmployeePhones>();
this.Leads = new HashSet<Lead>();
}
[Key]
public int PhoneID { get; set; }
public string PhoneNo { get; set; }
public virtual ICollection<Lead> Leads { get; set; }
}
public partial class LeadStatus
{
public LeadStatus()
{
this.Leads = new HashSet<Lead>();
}
[Key]
public int LeadStatusID { get; set; }
public string Status { get; set; }
public virtual ICollection<Lead> Leads { get; set; }
}
I've also corrected the plurality of your classes. Lead vs Leads. The class describes a single lead, so it should be called Lead not Leads. Phone vs Phones.
I need to map a model to a viewmodel using AutoMapper.
Model:
[Table("News")]
public class News
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public DateTime DatePostedOn { get; set; }
public int Position { get; set; }
public Category Category { get; set; }
public virtual ICollection<Picture> Pictures { get; set; }
}
[Table("Pictures")]
public class Picture
{
[Key]
public int Id { get; set; }
public DateTime DateCreated { get; set; }
public string Filename { get; set; }
public int Type { get; set; }
public virtual ICollection<News> News { get; set; }
}
Viewmodel:
public class HomeViewModels
{
public IList<HomeMainNews> MainNews { get; private set; }
}
public class HomeMainNews
{
public int Id { get; set; }
public string Title { get; set; }
public string Date { get; set; }
public string PictureURL { get; set; }
}
Mapping:
Mapper.CreateMap<News, HomeMainNews>();
How can I map a News that have a set of Pictures, to a viewmodel with only one picture according to a certain condition "Type = 2"
Current solution:
vm.MainNews = db.News
.Select(n => new HomeMainNews {
Id = n.Id,
Date = n.DatePostedOn.ToString(),
Title = n.Title,
PictureURL = n.Pictures.Where(p => p.Type == 1).Select(p => p.Filename).FirstOrDefault().ToString()
}).ToList();
Automapper solution:
vm.MainNews = db.News.Project().To<HomeMainNews>().ToList();
Try this
Mapper.CreateMap<News, HomeMainNews>()
.ForMember(mainNew => mainNew.Date, opt => opt.MapFrom(news => news.DatePostedOn))
.ForMember(mainNew => mainNew.PictureURL, opt => opt.MapFrom(news => news.Pictures.First(pic => pic.Type == 2).Filename));
Should T be a for example Customer or CustomerViewModel ?
The annotations bound to Mvc namespace are on the ListViewModel so actually I could pass the Customer object. What do you think?
public class ListViewModel<T>
{
[Required(ErrorMessage="No item selected.")]
public int[] SelectedIds { get; set; }
public IEnumerable<T> DisplayList { get; set; }
}
UPDATE
[HttpGet]
public ActionResult Open()
{
IEnumerable<Testplan> testplans = _testplanDataProvider.GetTestplans();
OpenTestplanListViewModel viewModel = new OpenTestplanListViewModel(testplans);
return PartialView(viewModel);
}
public class OpenTestplanListViewModel
{
public OpenTestplanListViewModel(IEnumerable<Testplan> testplans)
{
var testplanViewModels = testplans.Select(t => new TestplanViewModel
{
Name = string.Format("{0}-{1}-{2}-{3}", t.Release.Name, t.Template.Name, t.CreatedAt, t.CreatedBy),
TestplanId = t.TestplanId,
});
DisplayList = testplanViewModels;
}
[Required(ErrorMessage = "No item selected.")]
public int[] SelectedIds { get; set; }
public string Name { get; set; }
public IEnumerable<TestplanViewModel> DisplayList { get; private set; }
}
public class TestplanViewModel
{
public int TestplanId { get; set; }
public string Name { get; set; }
}
public class Testplan
{
public int TestplanId { get; set; }
public int TemplateId { get; set; }
public int ReleaseId { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedAt { get; set; }
public Template Template { get; set; }
public Release Release { get; set; }
}
T should ideally be a view model. Having a view model referencing domain models is some kind of a hybrid view model, not a real one. But if you think that in this specific case the domain model will be exactly the same as the view model then you could keep it as well.