J0NNY ZER0
J0NNY ZER0

Reputation: 707

MVC3 actionlink attaches ID to Object

I have a an object view with data and a button on that view. The user can review the object info and click the button to go to a new view form whee he can enter info to create an item. My challenge is this, how would I attach the ID of the object on the previous view to associate it with and attach to the information they create and submit?

Upvotes: 1

Views: 655

Answers (2)

Shyju
Shyju

Reputation: 218732

@Html.ActionLink("Add","AddNotes","Object",new {@id=5},null)

This will create an a tag with querystring ?id=5. (You may replace the hardcoded 5 with the dynamic value in your view)

Have a property to keep this value for your ViewModel/Model for the create form.

public class CreateNoteViewModel
{
  public int ParentId { set;get;}
  public string Note { set;get;}
  //Other properties also
}

Read this in your GET action method which creates the second view and set the value of that property of the ViewModel/Model.

public ActionResult AddNotes(int id)
{
  var model=new CreateNoteViewModel();
  model.ParentId=id;
  return View(model);
}

And in your strongly typed view, Keep this value inside a hidden variable.

@model CreateNoteViewModel
@using(Html.BeginForm())
{
 @Html.TextBoxFor(Model.Note)
 @Html.HiddenFor(Model.ParentId)
 <input type="submit" />
}

Now in your HttpPost action , you can get the Object Id from your POSTED model's ParentId property

[HttpPost]
public ActionResult AddNotes(CreateNoteViewModel model)
{
 if(ModelState.IsValid()
 {
   //check for model.ParentId here
   // Save and redirect
 }
 return View(model); 
}

Upvotes: 1

user1166147
user1166147

Reputation: 1610

You could use hidden input & viewdata, PSEUDOCODE. NOTE you may have to use strings with view data and convert back to your id in your controller. See this link for a basic explanation of ViewData/ViewBag (and cons).

You'll need to pass the data to the view from the first action (Controller) The Controller base class has a "ViewData" dictionary property that can be used to populate data that you want to pass to a View. You add objects into the ViewData dictionary using a key/value pattern.

controller

 public ActionResult yourfirstaction()
      {
            //assign and pass the key/value to the view using viewdata
            ViewData["somethingid"] = ActualPropertyId;

in view - get the value use it with the hidden input to pass back to next controller to render next view

 <input type="hidden" name="somethingid" value='@ViewData["somethingid"]' id="somethingid" />

controller

  public ActionResult yournextaction(string somethingid)
      {
            //use the id
            int ActualPropertyId =  Convert.ToInt32(somethingid);

Upvotes: 0

Related Questions