开发者

creating a create/edit view/action with SelectList in asp.net mvc

开发者 https://www.devze.com 2022-12-11 03:01 出处:网络
the basic idea is that you have some class that has a reference type property, something like this public class Person

the basic idea is that you have some class that has a reference type property, something like this

public class Person 
{
   public int Id { get; set; }
   public string Name { get; set; }
   public Country HomeCountry { get; set; }
}

public class Country 
{
   public int Id { get; set; }
   public string Name { get; set; }
}

now if you need to create a view to edit Person's data you don't have any problems with Name or Id, but you do have with Country;

at the moment i have two basic solutions

nr1: in the action method i put ViewData["Countries"] = countryService.GetAll(); and use it in the view with something like this SelectList(ViewData["Countries"], Country.Id

and i'm gonna have [the post action] Create(Country country)

nr2: Create a PersonDto or PersonViewModel (same thing i guess)

here i'm gonna have Create(CountryVieModel countryViewModel) and no usage of ViewData

 public class PersonViewModel
     {
     Person Person { get; set; }
     public SelectList Countries { get; private set; }


     public PersonViewModel(Person person) 
     {
     Person = person;
     var countryService = container.Resolve<CountryService>();
     Countries = new SelectList(countryService.GetAll(),Person.Country);
     }

   }

but I feel like there should some way better than the开发者_如何学编程se two

anybody knows the best way to do this ?


Yes, nr2 is the best.

0

精彩评论

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

关注公众号