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