【问题标题】:How to fetch type of form collection values in mvc如何在 mvc 中获取表单集合值的类型
【发布时间】:2016-03-25 12:04:26
【问题描述】:

我有一个表单在序列化后使用 ajax 发送到控制器。我想在控制器中获取值类型为 int 或 string。表单具有输入类型文本和输入类型编号?如何获取输入类型号的类型为 int ? 控制器代码如下

 string abc = fm[key].GetType().Name;

这总是“字符串”。

假设您有一个如下所示的表单

<form method='Post' action='../Home/Index'>
  <input type="text" name="First"/>
  <input type="number" name="Second"/>
  <input type="submit" value="send"/>
</form>

在控制器端循环键和值并将它们添加到存储过程参数中。但是sp还有一个参数作为类型,例如字符串,整数......

控制器如下

[HttpPost]
public ActionResult Index(FormCollection fm)
{
    foreach (var key in fm.AllKeys)
    {
        using (SqlCommand command = new  SqlCommand("SysDefinitionPopulate", con))
        {
            string abc = fm[key].GetType().Name;
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add("@key", key);
            command.Parameters.Add("@value", fm[key]);
            command.Parameters.Add("@type", abc);
            command.ExecuteScalar();
        }
    }
}

【问题讨论】:

  • 请提供您的代码

标签: c# ajax asp.net-mvc formcollection


【解决方案1】:

FormCollection 是一个特殊的字典,其键和值都是字符串。

要获取整数,您可以创建一个自定义模型,而不是使用“FormCollection”这个模型,例如:

public class MeaningfulName
{
    public string First { get; set; }
    public int Second { get; set; }
}

在您的控制器中:

[HttpPost]
public ActionResult Index(MeaningfulName model)
{             
     using (SqlCommand command = new  SqlCommand("SysDefinitionPopulate", con))
     {
         command.CommandType = CommandType.StoredProcedure;
         command.Parameters.Add("@key", model.First);
         command.Parameters.Add("@value", model.Second);
         command.ExecuteScalar();
     }
}

【讨论】:

  • 好吧,我会尝试不同的。搜索后我看到了这个。感谢您的回答。
【解决方案2】:

最好不要使用 FormCollection - 改用模型绑定!

例如像这样的简单绑定:

[HttpPost]
public ActionResult Index(string First, int Second)
{
    // do your magic
}

或者使用实际的模型类:

public class TestModel // put in Models folder
{
    public string First { get; set; }
    public int Second { get; set; }
}

[HttpPost]
public ActionResult Index(TestModel myData)
{
    // do your magic
}

【讨论】:

  • 感谢您的建议,但我的观点是 List。我想这样做,因为你回答了很多:) 但有时情况可能会有所不同。
猜你喜欢
  • 2015-04-06
  • 1970-01-01
  • 1970-01-01
  • 2010-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-18
  • 2017-08-16
相关资源
最近更新 更多