2016-03-25 8 views
0

シリアル化した後にajaxでコントローラに送信するフォームがあります。値の型をint型またはコントローラ型の文字列として取得したいと思います。フォームには入力型のテキストと入力型の番号がありますか?どのようにint型の入力型の型を取り出すことができますか? 以下のコントローラコードmvcでフォームコレクション値の型を取り出す方法

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(); 
     } 
    } 
} 
+0

使用 '.GetTypeを()' –

+0

は –

答えて

2

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(); 
    } 
} 
+0

[OK]を、その後、私は別のSTHしようとするあなたのコードを提供してください。検索後、私はこれを見た。ご回答ありがとうございます。 – mayk

0

ベター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 
} 
+1

ご意見ありがとうございましたが、私の見解はリストです。私はあなたが多く答えるときにそれをしたい:)しかし時には条件が異なることがあります。 – mayk

関連する問題