简体   繁体   中英

How do you pass data from one view to another using the same controller but different actions? ASP.Net & Microsoft Graph

Okay, so the idea is that the user clicks on a dropdown selection on the view, hits Submit on the form, which sends the user choice back to the Controller, and renders a new view specific to that user choice.

This is the view:

<form method="post">
    <label for="teamList">First choose a team:</label>
    <select id="teamList" name="ID">
        @foreach (var item in Model)
        {
            <option value=@item.Id>@item.DisplayName</option>
        }
    </select><br />
    <input type="submit" value="Get channels">
</form>

The post method on the form would take the value of the user option and pass it to the Controller with action 'Index':

[HttpPost]
    public async Task<ActionResult> Index(string ID)
    {
        var data = await GraphHelper.GetChannelsAsync(ID);

        return View("Channels", data);

    }

Now it does render a 'Channels' view with the below html:

<form method="post">
    <label for="channelList">Now choose a channel:</label>
    <select id="channelList" name="channelId">
        @foreach (var item in Model)
        {
            <option value=@item.Id>@item.DisplayName</option>
        }
    </select><br />
    <input type="submit" value="Create tabs">
</form>

Now, here is where I need some help. I need to submit this channelList form again to create a tab using the Microsoft Graph API. I would submit this 'channelList' form back to my controller with the 'channelId' value.

public async Task<ActionResult> SubmitChannelId()
        {
            //Take channelID and pass it to microsoft.graphApi function call here
            return View(//with returned function call response);
        }

How can I do a [HttpPost] submit request on this 'Channels' view if I'm using the same controller? This probably has something to do with actions, or actionLinks but I've read that documentation and couldn't make sense of it. Can I get some assistance? Thanks!

Quick solution would be to just use the Url helper on form element:

<form method="post" action="@Url.Action("MyAction", "MyController")" >

You could as well use Html.BeginForm to render whole form:

@using(Html.BeginForm("MyAction", "MyController", FormMethod.Post))
{
    < ... >
}

In both cases your action SubmitChannelId in Controller should be decorated with [HttpPost] and accept input param of submited channelId (change type of param accordingly):

[HttpPost]
public async Task<ActionResult> SubmitChannelId(int channelId)
{
    < ... >
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM