shifa fatima
shifa fatima

Reputation: 63

Passing data from Controller to model in MVC 3

is there a way to pass data from controller to model?

the scenario of my project is that, it has two tables in database, and in View there are two text boxes , the data of one text box is save to one table while data of another table is save to another table , i want to show the data of both tables in another single View . for that reason i want to send both textbox values from controller to model then want to show the data from that model to the view. can someone please help how can i implement it ?

Upvotes: 0

Views: 6657

Answers (1)

Shyju
Shyju

Reputation: 218872

You need to create a view model and use that. view model's are simple POCO classes which are specific to the view.

public class CustomerInfo
{ 
  public string Name {set;get;}
  public string AddressLine {set;get;}
}

And in your GET Action, you can create an object of this, read the data from 2 tables and set the property values of our view model and send to the view

public ActionResult View(int id)
{
   var vm = new CustomerInfo();
   var db=new YourDbContext();

   var customer=db.GetCustomer(id); // read from first table
   var address=db.GetAddress(id);   // read from second table
   vm.Name = customer.FirstName;
   vm.AdddressLine = address.AddressLine1;
   return View(vm);
}

And your view will be strongly typed to this view model

@model CustomerInfo
<h2>@Model.Name</h2>
<h3>@Model.AddressLine1</h3>

If you are trying to save this information to the db tables, You may have a form in your view

@model CustomerInfo
@using(Html.BeginForm("Edit","Home"))
{
 <label>Name</label> @Html.TextBoxFor(f=>f.Name)
 <label>Name</label> @Html.TextBoxFor(f=>f.AddressLine)
 <input type="submit" />
}

and in your HttpPost action

[HttpPost]
public ActionResult Edit(CustomerInfo model)
{
   // read the values from model and save to 2 tables
   var c=new Customer { FirstName=model.Name};
   var a=new Address{ AddressLine1=model.AddressLine};

   var db=new YourDbContext();
   db.Customers.Add(c);
   db.Addresses.Add(a);
   db.SaveChanges();
   return RedirecToAction("Success");
}

If you want to save a collection of items, You may refer this answer or this.

Upvotes: 1

Related Questions