开发者

Best method to pass value in MVC

开发者 https://www.devze.com 2023-03-13 04:04 出处:网络
I am still new to MVC, so sorry if this is an obvious question: I have a page where the user can choose one of several items. When they select one, they are taken to another form to fill in their det

I am still new to MVC, so sorry if this is an obvious question:

I have a page where the user can choose one of several items. When they select one, they are taken to another form to fill in their details.

What is the best way to transfer that value to the form page? I don't want the ID of the item in the second (form) pages URL.

so it's /choose-your-item/ to /redemption/ where the user sees what was selected, and fills the form in. The item selected is displayed, and shown in a hidden form.

I guess one option is to store in a session before the redirect, but 开发者_JS百科was wondering if there was another option.

I am using MVC3


Darin Dimitrov's answer would be best if you don't need to do any additional processing before displaying the /redemption/ page. If you do need to some additional processing, you're going to have to use the TempDataDictionary to pass data between actions. Values stored in the TempDataDictionary lasts for one request which allows for data to be passed between actions, as opposed to the values stored in the ViewDataDictionary which only can be passed from an action to a view. Here's an example below:

public ActionResult ChooseYourItem()
{
    return View();
}

[HttpPost]
public ActionResult ChooseYourItem(string chosenItem)
{
    TempData["ChosenItem"] = chosenItem;

    // Do some other stuff if you need to

    return RedirectToAction("Redemption");
}

public ActionResult Redemption()
{
    var chosenItem = TempData["ChosenItem"];

    return View(chosenItem);
}


If you don't want the selected value in the url you could use form POST. So instead of redirecting to the new page, you could POST to it:

@using (Html.BeginForm("SomeAction", "SomeController"))
{
    @Html.DropDownListFor(...)
    <input type="submit" value="Go to details form" />
}


To help others, this is how I resolved my issue of needing multiple buttons posting back, and wanting to pass a different Id each time.

I have a single form on the page, that posts back to my controller:

The Form:

        @using (Html.BeginForm("ChooseYourItem", "Item", FormMethod.Post))
        {

And the code

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult ChooseYourItem(string itemId)
    {
        TempData["ITEMID"] = itemId

        return RedirectToAction("Create", "Redemption");
    }

Then, inside the form, I create buttons whose name == "itemId", but has a different value each time.

For example

<strong>Item 1</strong>
<button value="123" name="itemid" id="btn1">Select</button>

<strong>Item 2</strong>
<button value="456" name="itemid" id="btn2">Select</button>
0

精彩评论

暂无评论...
验证码 换一张
取 消