0

I have a form that sending to controller with ajax after serializing. I want to fetch the values type as int or string in controller.The form has input type text and input type number? how can i fetch the type of input type number as int ? Controller code as below

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

This is getting always 'String'.

Assume you have a form in view as below

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

In controller side looping the keys and values and adding them to the stored procedure parameters. But the sp has also a parameter as type such as string,integer...

The controller as below

[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();
        }
    }
}
1
  • please provide your code Commented Mar 25, 2016 at 12:08

2 Answers 2

1

FormCollection is a special dictionary both keys and values of which are strings.

To get integer you can create a custom model and instead of 'FormCollection' use this model, e.g.:

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

In your controller:

[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();
     }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ok then, i will try sth different. After search i saw this. Thanks for answer.
0

Better not use FormCollection - use Model Binding instead!

E.g. simple binding like this:

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

Or using an actual model class:

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 Comment

Thanks your suggestion but my view taking List<dynamic>. I want to do it as you answer a lot :) but sometimes the condition can be different.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.