韧皮实践:ASP.NET MVC控制器/动作与多个对象类型 [英] Bast Practise: ASP.NET MVC Controller/Action with multiple object types

查看:90
本文介绍了韧皮实践:ASP.NET MVC控制器/动作与多个对象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找的以下问题我有最好的方法。

I'm looking for the best method for the following issue I have.

我当前有大量所有继承为单个基础对象和都是非常类似的对象。是否有解决方案可用的将允许无需复制很多相同code的一个创建行动和一个编辑操作。

I current have a large number of objects that all inherit for a single base object and are all very similar. Is there a solution available the will allow one create action and one edit action without needing to replicate a lot of the same code.

例如,我可能有一个人对象:

So for example I might have a person object:

public class PersonBase
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
}

然后,我将有一个数量的对象从人继承这样的:

public class SalesPerson : PersonBase
{
  public double TotalCommission { get; set; }
}

public class Customer: PersonBase
{
  public string Address { get; set; }
}

现在目前我有这将创建一个客户群的行动:

Now currently I have an action that will create a customer base:

[HttpPost]
public virtual ActionResult Create(FormCollection collection)
{
  var person = new PersonBase();

  UpdateModel(person);

  if ( Model.IsValid && person.IsValid )
  {
    // Save to the db
  }

  return View();
}

现在我可以很容易地复制此code和修改,这样我就可以建立一个销售员和客户,但我将不得不关闭基于PersonBase大量的对象,这将是一个很多类似$ C $的重复ç,我想避免的。

Now I can quite easily copy this code and modify it so I can create a salesPerson and customer but I will have a large number of objects based off PersonBase and it would be a lot of repetition of similar code which I would like to avoid.

正在为所有类型的人呢?

Is the way of making the Create action more generic for all types of Person?

感谢

推荐答案

我发现的解决方案,为我工作是使用动态从C#4,所以,我的code相类似:

The solution I found that worked for me was to use the dynamic from C# 4. So my code looks like:

[HttpPost]
public virtual ActionResult Create(int type, FormCollection collection)
{
      dynamic person = new PersonBase();

      if ( type == 1 )
        person = new SalesPerson();
      else if ( type == 2 )
        person = new Customer();

      UpdateModel(person);

      if ( Model.IsValid && person.IsValid )
      {
        // Save to the db
      }

      return View();
}

这篇关于韧皮实践:ASP.NET MVC控制器/动作与多个对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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