Retrieving Data Using Form Collection and Inserting Into ASP.Net MVC

Retrieving Data Using Form Collection and Inserting Into ASP.Net MVC

In this tutorial we have learn Retrieving Data Using Form Collection and Inserting Into ASP.Net MVC,A Form Collection is the data that is passed in a form submission when we use the HTTP POST Method

There are various ways to pass data from view to an action.

  • Form Data.
  • Model Binding.
  • Parameterized Query.

Step 1 : First Create sql database with table and Add model with following code

namespace Mvc_formCollection.Models
{
public class Employee
{
public int id { get; set; }
[Required]
public string name { get; set; }
[Required]
public string city { get; set; }

SqlConnection con = new SqlConnection(@”Data Source=(LocalDB)\v11″);

public void insert_data(Employee emp)
{
con.Open();
SqlCommand cmd = new SqlCommand(“insert into tbl_user values(‘” + emp.name + “‘,'” + emp.city + “‘)”, con);
cmd.ExecuteNonQuery();
con.Close();
}

Step 2 : Now create the controller and add given code as mentioned

public class ABCController : Controller
{
public ActionResult Insert(FormCollection ff)
{
if (ModelState.IsValid)
{
Employee emp = new Employee();
emp.name = ff[“name”];
emp.city = ff[“city”];
emp.insert_data(emp);
}
return View();
}
}

Step 3: Now add view for above Insert Operation

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

<fieldset>
<legend>Employee</legend>

<div class=”editor-label”>
@Html.LabelFor(model => model.name)
</div>
<div class=”editor-field”>
@Html.EditorFor(model => model.name)
@Html.ValidationMessageFor(model => model.name)
</div>

<div class=”editor-label”>
@Html.LabelFor(model => model.city)
</div>
<div class=”editor-field”>
@Html.EditorFor(model => model.city)
@Html.ValidationMessageFor(model => model.city)
</div>

<p>
<input type=”submit” value=”Create” />
</p>
</fieldset>
}

Now create code as per above mentioned code and check output, if you need any help reguardind Retrieving Data Using Form Collection and Inserting Into ASP.Net MVC , than feel free to comment on comment section.

SEE MORE

 

Facebook Notice for EU! You need to login to view and post FB Comments!