开发者

asp.net mvc 3 entity framework, passing model info in Get request of create action

开发者 https://www.devze.com 2023-03-30 03:09 出处:网络
I\'m having trouble passing view information from my Get/Create action to my view. Here are my three model classes;

I'm having trouble passing view information from my Get/Create action to my view. Here are my three model classes;

public class Competition
{
    public int Id { get; set; }
    public int CompetitionId { get; set; }
    public string Name { get; set; }
    public开发者_如何学运维 string Prize { get; set; }
}

public class CompetitionEntry
{
    public int Id { get; set; }
    public int CompetitionEntryId { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public int CompetitionId { get; set; }
}

public class CompetitionEntryViewModel
{
    public int Id { get; set; }
    public Competition Competitions { get; set; }
    public int CompetitionId { get; set; }
    public string Name { get; set; }
    public string Email { get; set; } 
}

Here is my Get/Create action in CompetitionEntry Controller;

public ActionResult Create(int id)
{
    CompetitionEntryViewModel competitionentryviewmodel = db.CompetitionEntriesView.Find(id);
    return View(competitionentryviewmodel);
}

I know this doesn't work. The id parameter goes into the URL fine. How to I get access to my Competition class in th Get action? I need to be able to show the competion name on my Create Competition entry view.

Thanks in advance!


public ActionResult Create(int id)
{
      var data = db.CompetitionEntriesView.Find(id);

      CompetitionEntryViewModel competitionentryviewmodel = new CompetitionEntryViewModel();
      competitionentryviewmodel.CompetitionName = data.Name;

      return View(competitionentryviewmodel);
}


What you are trying to do is build an object graph and display it through a view model. In order to do this, you need to map your domain model(s) to your view model.

You can do the mapping yourself by writing a lot of code (re-inventing the wheel), or, you could consider using third party tools to do this for you. I recommend you use an AutoMapper as it is very simple to use imo.

The other problem is that your view model contains a domain model. This is likely to cause you a lot of headache in near future. If I were you, I would replace Competition with CompetitionViewModel.

I would also consider creating a view model for a list of competitions, i.e. CompetitionsViewModel. Look into partial views to see how you can display a list of competitions.

Good luck

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号