I'm not sure what you mean by "it isn't really a good solution," since using hidden fields is potentially the cleanest method of persisting data across multiple posts. Bear in mind that HTTP is - and should be treated as - a stateless protocol. A few other options to consider, however:
Cookies
Add the value to a cookie in your controller and add it to the Response
object. Then, pick it up and read it as and when you need it using Request.Cookies
.
/* Setting */
Response.Cookies["id"].Value = "myId";
/* Getting */
var id = Request.Cookies["id"] != null
? Request.Cookies["id"].Value
: String.Empty;
Pros: Persist across multiple requests without having to do anything in the requests in between.
Cons: Easily switched off client-side.
Session state
Add the value to session state using the Session
collection.
/* Setting */
Session["id"] = "myId";
/* Getting */
var myId = Session["id"] != null ? Session["id"].ToString() : String.Empty;
Pros: Easy to use, persist across multiple requests
Cons: Can get very messy if the user has multiple tabs open, uses the 'Back' button, etc. Often unpredictable.
Hidden fields
Add the value to a hidden field and pick this value back up on the next POST.
/* View (assuming string model property 'Id') */
@Html.BeginForm("MyAction", "MyController")
{
@Html.HiddenFor(m => m.Id)
<input type="submit" value="Submit" />
}
/* Controller */
public ActionResult MyAction(MyModel model)
{
var id = model.Id;
}
Pros: No footprint. Clean, simple, stateless and efficient.
Cons: No good for persisting across GET requests. Only persists across one POST at a time.
Query string
Add the values as query string parameters on redirects.
/* View */
@Html.ActionLink("Go!", "MyAction", new { identifier = "myId" })
/* Controller */
public ActionResult MyAction(string identifier)
{
var id = identifier ?? String.Empty;
}
Pros: Unlike hidden fields, can be used for GET requests.
Cons: Requires you to implement a method of persisting the query string across all requests for which you need the values.
What's best?
Personally, I'd say that - in your case - using cookies is probably the best option. If you want to persist across multiple requests without having to handle the value in every single request (and without the horribleness of using Session
), cookies are likely to be the simplest and neatest approach.