3

在我的应用程序中,我创建了一个方法来对我的数据进行排序并创建一个传递给我的数据层的列表。我已经重载它以接受参数对象 [] 和模型。我正在编写接受模型的重载方法,但循环遍历它时遇到问题。

这是我的控制器方法

        [HttpPost]
        public ActionResult CreateUser(vw_UserManager_Model model)
        {
            // Return Model to view with error message when not valid.
            if (!ModelState.IsValid == true)
            {
                return View(model);
            }
            else
            {
                List<string> myParams = DataCleaner.OrganizeParams(model);
            }

这是我在将数据传递到数据层之前组织数据的方法

public static List<string> OrganizeParams(vw_UserManager_Model model)
        {
            List<string> myParams = new List<string>();

            var modelProperties = model.GetType().GetProperties();

            foreach (var property in model.GetType().GetProperties())
            {
                switch (property.PropertyType.Name)
                {
                    case "String":
                        myParams.Add("System.String" + ":" + property.GetValue(property.PropertyType.Name, null));
                        break;
                    case "Guid":
                        myParams.Add("System.Guid" + ":" + property.GetValue(property.PropertyType.Name, null));
                        break;
                    case "Int32":
                        myParams.Add("System.Int32" + ":" + property.GetValue(property.PropertyType.Name, null));
                        break;
                    case "Boolean":
                        myParams.Add("System.Boolean" + ":" + property.GetValue(property.PropertyType.Name, null));
                        break;
                }
            }
            return myParams;
        }

我在 Switch/Case 逻辑中所做的实际上不起作用,因为我在断点中查看了我的对象并且看不到我需要在代码中编写什么。我知道我也可以使用 IEnumerable,但我不太确定我想怎么做。

有什么建议么?

概括

如何在MVC3的代码文件中循环模型?

4

1 回答 1

2

这对我有用,但看起来你很接近:)

public static List<string> OrganizeParams(vw_UserManager_Model model)
{
    List<string> myParams = new List<string>();

    foreach (var property in model.GetType().GetProperties())
    {
        switch (property.PropertyType.GenericTypeArguments.FirstOrDefault().Name.ToString())
        {
            case "String":
                myParams.Add("System.String" + ":" + property.GetValue(model, null));
                break;
            case "Guid":
                myParams.Add("System.Guid" + ":" + property.GetValue(model, null));
                break;
            case "Int32":
                myParams.Add("System.Int32" + ":" + property.GetValue(model, null));
                break;
            case "Boolean":
                myParams.Add("System.Boolean" + ":" + property.GetValue(model, null));
                break;
        }
    }
    return myParams;
}
于 2014-02-20T07:25:39.640 回答