DropDownListFor how to use?

2

I'm having a question on how popular and then get the selected item from a DropDownListFor , I'm using DDD and Entity Framework architecture.

In the case here my class ServiceProviderViewModel has to have relationship with other classes. I would like to know how to make this Helper in View of Create popular.

Following codes:

public class ServiceProviderViewModel
{
    [Key]
    public int ServiceProviderId { get; set; }

    [Required(ErrorMessage = "Por favor, informe o nome do colaborador.")]
    [Display(Name = "Nome:")]
    public string Name { get; set; }

    [Display(Name = "Nome da Mãe:")]
    public string MotherName { get; set; }

    [Display(Name = "Nome do Pai:")]
    public string FatherName { get; set; }

    [Display(Name = "E-mail:")]
    [EmailAddress(ErrorMessage = "Por favor, informe um formato de e-mail válido.")]
    public string Email { get; set; }

    [Display(Name = "Nascimento:")]
    public DateTime Birth { get; set; }

    [ScaffoldColumn(false)]
    public DateTime DateRegister { get; set; }

    [ScaffoldColumn(false)]
    public DateTime DateModified { get; set; }

    [Required(ErrorMessage = "Por favor, informe o departamento para o colocaborador.")]
    [Display(Name = "Departamento:")]       
    public int DepartamentId { get; set; }

    [Required(ErrorMessage = "Por favor, informe o departamento para o colocaborador.")]
    [Display(Name = "Cargo/Função:")]
    public int PositionId { get; set; }

    public virtual DepartamentViewModel Departaments { get; set; }
    public virtual PositionViewModel Positions { get; set; }

    public virtual IEnumerable<ServiceProviderAddressViewModel> ServiceProviderAddress { get; set; }
    public virtual IEnumerable<ServiceProviderPhoneViewModel> ServiceProviderPhone { get; set; }
    public virtual IEnumerable<ServiceProviderInfoViewModel> ServiceProviderInfo { get; set; }
    public virtual IEnumerable<InfoBankViewModel> InfoBank { get; set; }
}

Controller :

 public class ServiceProviderController : Controller
{
    private readonly IServiceProviderAppService _serviceProviderApp;

    public ServiceProviderController(IServiceProviderAppService serviceProviderApp)
    {
        _serviceProviderApp = serviceProviderApp;
    }

    // GET: ServiceProvider
    public ActionResult Index()
    {
        var serviceProviderViewModel = Mapper.Map<IEnumerable<ServiceProvider>, IEnumerable<ServiceProviderViewModel>>(_serviceProviderApp.GetAll());
        return View(serviceProviderViewModel);
    }

    // GET: ServiceProvider/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: ServiceProvider/Create
    [HttpPost]
    public ActionResult Create(ServiceProviderViewModel serviceProvider)
    {
        if (ModelState.IsValid)
        {
            var serviceProviderDomain = Mapper.Map<ServiceProviderViewModel, ServiceProvider>(serviceProvider);
            _serviceProviderApp.Add(serviceProviderDomain);
            _serviceProviderApp.Save();

            return RedirectToAction("Index");
        }

        return View(serviceProvider);
    }

...

For each class that ServiceProvider relates I have the specific models for CRUD realization. I just do not know how I should work to run this mix of models and controllers .     

asked by anonymous 11.05.2016 / 21:00

3 answers

1

@uitan, this exception is masking the real problem that should be just validating your form. You must load the ViewBags of the post action as you did in the Get action. your post should look like this:

// POST: ServiceProvider/Create
[HttpPost]
public ActionResult Create(ServiceProviderViewModel serviceProvider)
{
    if (ModelState.IsValid)
    {
        var serviceProviderDomain = Mapper.Map<ServiceProviderViewModel, ServiceProvider>(serviceProvider);
        _serviceProviderApp.Add(serviceProviderDomain);
        _serviceProviderApp.Save();

        return RedirectToAction("Index");
    }

    //FALTAM ESSAS LINHAS:
    ViewBag.Position = new SelectList(_positionApp.GetAll(), "PositionId", "Description");
    ViewBag.Departament = new SelectList(_departamentApp.GetAll(), "DepartamentId", "Description");

    return View(serviceProvider);
}

Mark as resolved if it works. :)

    
18.05.2016 / 19:37
3

Code taking into account that PositionId should be a combo:

Na Action Get:

Obs: You should pass the ViewBag.Position

public ActionResult Create()
{
    ViewBag.Position = new SelectList(_serviceProviderApp.SeuMetodoDeObterPositions(), "PositionId", "SeuCampoDescricao");

    return View();
}

Na view:

Note: This Code places the first option blank and then the data coming from the ViewBag.

@Html.DropDownList("PositionId", (IEnumerable<SelectListItem>)ViewBag.Position, String.Empty, new { @class = "form-control" })
    
12.05.2016 / 22:12
0

No Domain:

 public class ServiceProvider
{
    #region Attributs
    public int ServiceProviderId { get; set; }
    public string Name { get; set; }
    public string MotherName { get; set; }
    public string FatherName { get; set; }        
    public string Email { get; set; }
    public DateTime Birth{ get; set; }
    public DateTime DateRegister { get; set; }
    public DateTime DateModified { get; set; }
    #endregion
    #region Foreingkeys
    public int DepartamentId { get; set; }
    public int PositionId { get; set; }
    #endregion
    #region Properties Navigations
    public virtual Departament Departaments { get; set; }
    public virtual Position Positions { get; set; }
    #endregion
}

public class Position
{
    #region Attributs
    public int PositionId { get; set; }
    public string Description { get; set; }
    public DateTime DateRegister { get; set; }
    public DateTime DateModified { get; set; }
    #endregion
    #region Relationships Other Class
    public virtual IEnumerable<ServiceProvider> ServiceProviders { get; set; }
    #endregion
}

 public class Departament
{
    #region Attributs
    public int DepartamentId { get; set; }
    public string Description { get; set; }
    public DateTime DateRegister { get; set; }
    public DateTime DateModified { get; set; }
    #endregion
    #region Relationships Other Class
    public virtual IEnumerable<ServiceProvider> ServiceProviders { get; set; }
    #endregion
}

In the ViewModel (Presentation Layer)

public class ServiceProviderController : Controller
{
    private readonly IServiceProviderAppService _serviceProviderApp;
    private readonly IPositionAppService _positionApp;
    private readonly IDepartamentAppService _departamentApp;

    public ServiceProviderController(IServiceProviderAppService serviceProviderApp, IPositionAppService positionApp, IDepartamentAppService departamentApp)
    {
        _serviceProviderApp = serviceProviderApp;
        _positionApp = positionApp;
        _departamentApp = departamentApp;
    }

    // GET: ServiceProvider
    public ActionResult Index()
    {
        var serviceProviderViewModel = Mapper.Map<IEnumerable<ServiceProvider>, IEnumerable<ServiceProviderViewModel>>(_serviceProviderApp.GetAll());
        return View(serviceProviderViewModel);
    }

    // GET: ServiceProvider/Details/5
    public ActionResult Details(int id)
    {
        return View();
    }

    // GET: ServiceProvider/Create
    public ActionResult Create()
    {
        ViewBag.Position = new SelectList(_positionApp.GetAll(), "PositionId", "Description");
        ViewBag.Departament = new SelectList(_departamentApp.GetAll(), "DepartamentId", "Description");
        return View();
    }

    // POST: ServiceProvider/Create
    [HttpPost]
    public ActionResult Create(ServiceProviderViewModel serviceProvider)
    {
        if (ModelState.IsValid)
        {
            var serviceProviderDomain = Mapper.Map<ServiceProviderViewModel, ServiceProvider>(serviceProvider);
            _serviceProviderApp.Add(serviceProviderDomain);
            _serviceProviderApp.Save();

            return RedirectToAction("Index");
        }

        return View(serviceProvider);
    }
}

In View:

<div class="form-group">
            @Html.LabelFor(model => model.DepartamentId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.DepartamentId, (IEnumerable<SelectListItem>)ViewBag.Departament, string.Empty)
                @Html.ValidationMessageFor(model => model.DepartamentId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PositionId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.PositionId, (IEnumerable<SelectListItem>)ViewBag.Position, string.Empty)
                @Html.ValidationMessageFor(model => model.PositionId, "", new { @class = "text-danger" })
            </div>
        </div>

The GetAll () and CRUD methods are called by generic repositories. The problem is exactly when I try to submit the form. Displays the error I mentioned earlier.

    
18.05.2016 / 02:13