最好的方式来填充的SelectList的视图模型上GET / POST [英] Best way to populate SelectList for ViewModel on GET/POST

查看:155
本文介绍了最好的方式来填充的SelectList的视图模型上GET / POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下视图模型:

public class EditViewModel
{
    public int FooType { get; set; }
    public IEnumerable<SelectListItem> FooTypes { get; set; }
}

我本来居住在我的编辑动作,像这样:

I originally populated it in my Edit action like so:

public ActionResult Edit(int id)
{
    EditViewModel model = new EditViewModel();
    model.FooTypes = new SelectList(repository.GetFooTypes(), "Id", "Value");

    return View(model);
}

当我创建张贴值的动作,我不得不重复同样的code:

When I created the action to POST the values I had to repeat the same code:

public ActionResult Edit(int id, EditViewModel model)
{
    if( !ModelState.IsValid )
    {
        model.FooTypes = new SelectList(repository.GetFooTypes(), "Id", "Value");

        return View(model);
    }

    return RedirectToAction("Index");
}

我不喜欢在两个不同的位置这code。是否有重构到一个单点这个,所以我不需要重复这个code任何常见的做法?

I don't like having this code in two separate locations. Is there any common practice for refactoring this into a single spot so I dont need to repeat this code?

推荐答案

由于C#是一种面向对象的语言,有很多可供选择。

Given that c# is an object oriented language, there are plenty of options available.

最简单的是只敷在控制器内的方法:

The simplest would be to just wrap it in a method within the controller:

private SelectList GetFooTypesList()
{
    return new SelectList(repository.GetFooTypes(), "Id", "Value);
}

和设置您的模型时调用它。

and call it when setting up your model

或者如果你在多个类中使用它,你可以创建在接受仓库里或者一个IEnumerable作为参数另一个类的辅助方法。

or if you're using it in multiple classes you could create a helper method in another class that accepts the repository or an IEnumerable as a parameter.

如果你想获得真正的高级技术,你可以使用一个ModelFactory为您创造了FooType模型,用prepopulated FooType属性,因此该控制器不需要担心它。

If you want to get really advanced, you could use a ModelFactory to create the FooType model for you, with a prepopulated FooType property so the controller doesn't need to worry about it at all.

有多种选择,你只需要挑选一个最适合你。

There's plenty of options, you just need to pick the one that's best for you.

我个人的preference是在控制器中的简单的辅助方法。

My personal preference is the simple helper method in the controller.

这篇关于最好的方式来填充的SelectList的视图模型上GET / POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆