开发者

Part of ViewModel lost on server side validation

开发者 https://www.devze.com 2023-02-18 00:09 出处:网络
I\'m new on ASP.NET MVC and I\'m having the following issue. Let\'s start with some code: ViewModel: public class StatesEditViewModel

I'm new on ASP.NET MVC and I'm having the following issue.

Let's start with some code:

ViewModel:

public class StatesEditViewModel
{
    [Required]
    public virtual int StateId { get; set; }
    [Required]
    public virtual string Name { get; set; }

    public virtual int CountryId { get; set; }
    public List<Country> Countries { get; set; }
}

Controller:

public ActionResult Edit(int id)
{
    using (DataEntities context = new DataEntities())
    {
        UnitOfWork uow = new UnitOfWork(context);

        State s = uow.States.GetById(id);

        StatesEditViewModel vm = new StatesEditViewModel();
        vm.StateId = s.StateId;
        vm.Name = s.Name;
        vm.CountryId = s.CountryId;

        vm.Countries = = uow.Country.GetAll().ToList<Country>();

        return View(vm);
    }
}


[HttpPost]
public ActionResult Edit(int id, StatesEditViewModel vm) 
{
    if (ModelState.IsValid)
    {
        using (DataEntities context = new DataEntities())
        {
            UnitOfWork uow = new UnitOfWork(context);

            State s = uow.States.GetById(id);
            p.Name = vm.Name;
            p.CountryId = vm.CountryId;

            uow.Commit();

            return RedirectToAction("Index");
        }
    }
    else 
    {
        //vm.Countries <-- This is NULL
        return View(vm开发者_如何学编程);
    }
}

The issue es that vm.Countries is null. Is there any option/solution to avoid having to re-populate that part of the ViewModel?

Just in case, I'm using the Telerik ComboBox controls in my view:

@(Html.Telerik().ComboBox()
        .Name("CountryId")
        .BindTo(new SelectList(Model.Countries, "CountryId", "Name"))
        .SelectedIndex(Model.CountryId)
        .Filterable()
)

Thanks!


The Countries collection is not part of the form so they are never posted to the server. Only the selected id is sent. So if the model is not valid and you need to render the view simply refetch this collection from the data store:

[HttpPost]
public ActionResult Edit(int id, StatesEditViewModel vm) 
{
    using (var context = new DataEntities())
    {
        if (ModelState.IsValid)
        {
            var uow = new UnitOfWork(context);
            State s = uow.States.GetById(id);
            p.Name = vm.Name;
            p.CountryId = vm.CountryId;
            uow.Commit();
            return RedirectToAction("Index");
        }
        // The model is not valid, we need to
        // redisplay the same view so that the
        // user can fix the errors => fetch the countries collection
        vm.Countries = uow.Country.GetAll().ToList<Country>();
        return View(vm);
    }
}
0

精彩评论

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

关注公众号