1

So I have a simple web app where I can create a user (UserModel) and it returns that user ID. The user then has the ability to enter multiple instances or records of a specific item type, in this case a geographic location (LocationModel). The LocationModel has a UserId property that I need to set when the location is created.

The ActionLink for creating a user is User/Create/id=[userid]

The code in the controller is currently.

[HttpGet]
public ActionResult Create(string id)
{
     return View();
}

[HttpPost]
public ActionResult Create(LocationModel model)
{
   //CODE TO SAVE MODEL
}

My questions is how to pass the user id so that I can get it into the model in order to relate the two. I was going to try to pass it in the ViewBag and render it in a Hidden field but was thinking that someone has to have a more elegant solution than this. Thanks in advance.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
jamesamuir
  • 1,397
  • 3
  • 19
  • 41

1 Answers1

3

Put the UserId on the model, and pass the model to the view:

[HttpGet]
public ActionResult Create(string id)
{
    return View(new LocationModel{UserId = id});
}

Then render the UserId property as a hidden field in the View, so it will get included on your model parameter when the form is POSTed.

@model LocationModel
@using (Html.BeginForm(...)) {
    @Html.HiddenFor(m => m.UserId)
    ...
}
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315