Jose3d
Jose3d

Reputation: 9277

Post form receiving a model in MVC3

I have the following model:

public class Person
{
    public int ID{get;set;}
    public string Name {get;set;}
    public string Address{get;set;}
}

For other hand i have the following view called Index:

@model List<Person>
@{

   foreach(Person person in Model)
   {
     <a href="#" id="@person.ID">@person.Name</a>
   }
}

Finally i have the following action:

public ActionResult Index()
{
     List<Person> persons=new List<Person>();
     persons.Add(new Person(){ID=1,Name="John"});
     persons.Add(new Person(){ID=2,Name="Tom"});
     persons.Add(new Person(){ID=2,Name="Derek"});
}

Im thinking to create a form (since i cannot use ajax for this app due to some requirements), to post an instance of the person chosen by the user (when clicks an anchor of my view). I would like to know how i could post a Person instance to another action described below (since my view is typed to a generic list of persons).

[HttpPost]
public ActionResult Index(Person person)
{
     ... Do whatever
}

Upvotes: 0

Views: 90

Answers (2)

Rafay
Rafay

Reputation: 31043

Solution with POST:

in order to work it with POST you will have to palce a form and plant hidden fields like

@model List<Person>
@{

   foreach(Person person in Model)
   { 
     <form action="/controller/actionresult">
     <input type="submit" value=person.Name />
     <input type="hidden" name="ID" value="@person.ID"
     <input type="hidden" name="Name" value="@person.Name"
     </form>
   }
}

and on the server side

[HttpPost]
public ActionResult Index(Person person)
{
     ... Do whatever
}

Solution with GET:

a tags normally dont work with POST there default behaviour is to request the server for a resource via GET although you can override this behaviour using javascript but in your case that is not an option therefore you can try

@model List<Person>
    @{

       foreach(Person person in Model)
       {
         @Html.ActionLink(persno.Name,"Index","home",new{ID=person.ID,Name=person.Name,null);      
       }
    }

the only drawback is you will have to use a submit button instead of a tags, you can use css styling to style the button like an a tag. also if you have not set custom routes for this kind of request the uri will have query string params like

http://yourdomain/home/index?ID=1&Name=john

Upvotes: 2

Dai
Dai

Reputation: 155726

You're approaching it from the wrong angle. As you're not presenting any way to edit a Person you should just pass it by reference (i.e. the PersonId).

So just use a straight-forward link:

// View:

Html.ActionLink( person.Name, "ViewPerson", new { personId = person.ID } );

// Controller action:

public ActionResult ViewPerson(String personId) {
    Person person = GetPersonFromDatabase( personId );
}

Upvotes: 2

Related Questions