填充MVC下拉列表 [英] Populate dropdown list in MVC

查看:121
本文介绍了填充MVC下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的MVC应用程序,我有一个服务调用(http://dev-service.test.com/api/brands?active=true)返回以下XML

In my MVC application, I have a service call (http://dev-service.test.com/api/brands?active=true) that returns the following XML

<Brands>
  <Brand>
  <BrandId>1</BrandId>
  <BrandNo>20</BrandNo>
  <BrandName>ABC</Domain>
  </Brand>

  <Brand>
  <BrandId>2</BrandId>
  <BrandNo>30</BrandNo>
  <BrandName>XYZ</Domain>
  </Brand>
<Brands>

在我的用户控件之一,我想填充一个DropDownList与名优产品值。我已经有一个包含一堆属性的视图模型。我如何填充值的下拉从这个XML?

In one of my user controls, I would like to populate a dropdownlist with the BrandName values. I already have a ViewModel that contains a bunch of properties. How can I populate the dropdown with the values from this XML?

P.S:我是新来的MVC和仍然在学习中的ViewModels等基础知识

P.S: I am new to MVC and still learning the basics of viewmodels etc.

推荐答案

有真有两部分在你的问题。 XML解析部分(其中有严格无关ASP.NET MVC)和ASP.NET MVC的一部分。由于您的问题是标记 asp.net-MVC 让我们先来回答这一部分。所以你提到一个视图模型。事情是这样的:

There really are 2 parts in your question. The XML parsing part (which has strictly nothing to do with ASP.NET MVC) and the ASP.NET MVC part. Since your question is tagged with asp.net-mvc let's first answer this part. So you mention a view model. Something like this:

public class BrandsViewModel
{
    public string Brand { get; set; }
    public IEnumerable<SelectListItem> Brands { get; set; }
} 

然后控制器动作:

then a controller action:

public ActionResult Index()
{
    BrandsViewModel model = ...
    return View(model);
}

和最后视图部分:

@model BrandsViewModel
@using (Html.BeginForm())
{
    @Html.DropDownListFor(x => x.Brand, Model.Brands)      
    <button type="submit">OK</button>
}

好吧,这是那里的ASP.NET MVC的一部分你的问题中结束。现在到了XML解析的一部分。有几种方法在C#来解析XML。例如,你可以使用的XDocument 类。

当然能够解析XML之前,你需要有XML。你已经在你的问题中所示是不是XML。它是一个字符串。你需要首先解决它,并有一个有效的XML。像这样的:

Of course before being able to parse XML you need to have XML. What you have shown in your question is not XML. It is a string. You need to first fix it and have a valid XML. Like this:

<Brands>
  <Brand>
    <BrandId>1</BrandId>
    <BrandNo>20</BrandNo>
    <BrandName>ABC</BrandName>
  </Brand>

  <Brand>
    <BrandId>2</BrandId>
    <BrandNo>30</BrandNo>
    <BrandName>XYZ</BrandName>
  </Brand>
</Brands>

现在,你有有效的XML让我们继续前进并使用XML解析器。

Now that you have valid XML let's move on and use a XML parser.

var brands =
    from brand in XDocument.Load("brands.xml").Descendants("Brand")
    select new SelectListItem
    {
        Value = brand.Element("BrandId").Value,
        Text = brand.Element("BrandName").Value
    };

现在让我们把这个2一起工作:

and now let's make the 2 work together:

public ActionResult Index()
{
    var brandsFile = Server.MapPath("~/app_data/brands.xml");
    var brands =
        from brand in XDocument.Load(brandsFile).Descendants("Brand")
        select new SelectListItem
        {
            Value = brand.Element("BrandId").Value,
            Text = brand.Element("BrandName").Value
        };


    var model = new BrandsViewModel
    {
        Brands = brands
    };
    return View(model);
}

这是在这里我们可以看到,我们已经强烈耦合输出控制器动作逻辑和XML解析逻辑,是坏的。你可以引入其中将注入控制器的构造,然后由动作中使用的抽象(接口)。然后,你可以提供一个具体的实施这种抽象的,将执行实际的XML解析和配置您的依赖注入框架将它传递给控制器​​。

This is where we can see that we have strongly coupled out controller action logic with XML parsing logic which is bad. You could introduce an abstraction (interface) which will be injected into the controller's constructor and then used by the action. Then you could provide a specific implementation of this abstraction that will perform the actual XML parsing and configure your dependency injection framework to pass it to the controller.

因此​​,让我们做到这一点。让我们来定义的域模型,将重新present我们的品牌:

So let's do that. Let's define a domain model that will represent our brands:

public class Brand
{
    public string Id { get; set; }
    public string Name { get; set; }
}

酷。现在我们怎么想那些品牌呢?检索它们的列表。让我们来定义我们的合同:

Cool. Now what do we want to do with those brands? Retrieve a list of them. Let's define our contract:

public interface IBrandsRepository
{
    Brand[] Get();
}

OK,我们已经指定我们需要与我们的品牌什么操作。现在,我们可以有我们的控制器是这样的:

OK, we have specified what operations we need with our brands. Now we could have our controller look like this:

public class BrandsController: Controller
{
    private readonly IBrandsRepository _repository;
    public BrandsController(IBrandsRepository repository)
    {
        _repository = repository;
    }

    public ActionResult Index()
    {
        var brands = _repository.Get().Select(b => new SelectListItem
        {
            Value = b.Id,
            Text = b.Name
        });
        var model = new BrandsViewModel
        {
            Brands = brands
        };
        return View(model);
    }
}

还有余地,这个控制器动作的改进。请注意,我们正在查询资料库,并获得领域模型的列表(品牌)及本领域模型转换成视图模型。这是繁琐,污染我们的控制器逻辑。这将是更好的外部化这个映射到一个单独的层。我个人使用 AutoMapper 了点。这是一个lightwight框架,允许您定义不同阶层之间的映射在一个流畅的方式,然后只需将它传递源类型的实例,它会吐出你的目标类型的实例:

There is still room for improvement in this controller action. Notice that we are querying the repository and obtaining a list of domain models (Brand) and converting this domain model into a view model. This is cumbersome and pollutes our controller logic. It would be better to externalize this mapping into a separate layer. Personally I use AutoMapper for that. It's a lightwight framework which allows you to define the mappings between different classes in a fluent way and then simply pass it instances of the source type and it will spit you instances of the target type:

public class BrandsController: Controller
{
    private readonly IBrandsRepository _repository;
    public BrandsController(IBrandsRepository repository)
    {
        _repository = repository;
    }

    public ActionResult Index()
    {
        var brands = _repository.Get();
        var model = new BrandsViewModel
        {
            Brands = Mapper.Map<IEnumerable<Brand>, IEnumerable<SelectListItem>>(brands)
        };
        return View(model);
    }
}

因此​​我们在这里取得进展。现在,我们可以有我们的合同的实现:

So we are making progress here. Now we could have an implementation of our contract:

public class BrandsRepositoryXml: IBrandsRepository
{
    private readonly string _brandsFile;
    public BrandsRepositoryXml(string brandsFile)
    {
        _brandsFile = brandsFile;
    }

    public Brand[] Get() 
    {
        return
            (from brand in XDocument.Load(_brandsFile).Descendants("Brand")
             select new Brand
             {
                 Id = brand.Element("BrandId").Value,
                 Name = brand.Element("BrandName").Value
             })
             .ToArray();
    }
}

和拼图的最后一步是配置一些DI框架来注入我们的合同到控制器的正确实施。有喜欢DI的gazzilion针对.NET框架。只需选择之一。这其实并不重要。尝试Ninject.MVC3的NuGet。这是有点酷,易于安装。或者,如果你不想使用第三方DI框架只需编写一个自定义的依赖解析器

And the last step of the puzzle is to configure some DI framework to inject the proper implementation of our contract into the controller. There are like a gazzilion of DI frameworks for .NET. Just pick one. It doesn't really matter. Try the Ninject.MVC3 NuGet. It's kinda cool and easy to setup. Or if you don't want to use third party DI frameworks simply write a custom dependency resolver.

这篇关于填充MVC下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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