简体   繁体   中英

Populating Html.BeginForm drop down with data from HttpGet method

I am working with Jira Rest Api and I am trying to create a form that will include a dropdown with all the users from certain project, so I could assign them while creating a ticket.

My form works But unfortunnetly Users have to be hardcoded at the moment.

I am a novice programmer and my problem begins here: I am usign HttpPost to submit form and pass that values to Api, but before I do that I need to do HttpGet to populate one of the form dropdowns. This is confusing for me and I am not able to do that.

My Form

                @using (Html.BeginForm("Index", "Ticket", FormMethod.Post))
                {
                    <div>
                        <br />
                        <div style="background-color:#1976D2; color: white; padding: 3px; border-radius:3px; font-weight: 300;">
                            <a>Create Issue</a>
                        </div>
                        <br />
                        <form>
                            <span style="font-size: 0.9em">Project</span> @Html.DropDownListFor(m => model.fields.project.key, new List<SelectListItem> { new SelectListItem { Text = "Jira Test Board", Value = "JATP" }, }, new { @class = "form-control input-background" })
                            <br />
                            <span style="font-size: 0.9em">Issue type</span> @Html.DropDownListFor(m => model.fields.issuetype.name, new List<SelectListItem> { new SelectListItem { Text = "Sales", Value = "Sales" }, new SelectListItem { Text = "Bug", Value = "Bug" }, new SelectListItem { Text = "Feature", Value = "Feature" }, new SelectListItem { Text = "Task", Value = "Task" }, }, new { @class = "form-control input-background" })
                            <br />

                            <span style="font-size: 0.9em">Assign<sup class="star">*</sup></span> @Html.DropDownListFor(m => model.fields.assignee.name, new List<SelectListItem> { new SelectListItem { Text = "Jacob Zielinski", Value = "<someId>" }, }, new { @class = "form-control input-background" })
                            <br />

                            <span style="font-size: 0.9em">Summary<sup class="star">*</sup></span> @Html.TextBoxFor(m => model.fields.summary, new { @class = "form-control my-size-text-area input-background" })
                            <br />
                            <div class="form-group">
                                <span style="font-size: 0.9em">Description<sup class="star">*</sup></span> @Html.TextAreaFor(m => model.fields.description, 5, 60, new { @class = "form-control my-size-text-area input-background" })
                            </div>
                            <br />
                            <input onclick="loadingOverlay()" id="Submit" class="btn btn-primary float-right" type="submit" value="Create" />
                        </form>
                    </div>
                }

Ticket Controller

  public class TicketController : Controller
{
    [HttpPost]
    public  async Task<ActionResult> Index(TokenRequestBody model)
    {
        var submitForm = new TokenRequestBody()
        {
            fields = new TokenRequestField()
            {
                project = model.fields.project,
                description = model.fields.description,
                summary = model.fields.summary,
                issuetype = model.fields.issuetype,
                assignee = model.fields.assignee
            },
        };

        using (var httpClient = new HttpClient())
        {

            httpClient.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue(
                    "Basic", Convert.ToBase64String(
                        System.Text.ASCIIEncoding.ASCII.GetBytes(
                           $"login:password"))); 
            var httpRequestMessage = new HttpRequestMessage();
            httpRequestMessage.Method = HttpMethod.Post;
            httpRequestMessage.RequestUri = new Uri("<company>atlassian.net/rest/api/2/issue/");
            httpRequestMessage.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(submitForm), Encoding.UTF8, "application/json");
            var response = httpClient.SendAsync(httpRequestMessage).Result;

            string responseBody =  await response.Content.ReadAsStringAsync();

            var jiraResponse = JsonConvert.DeserializeObject<TicketResponseBody>(responseBody);

            TempData["Message"] = "Ticked Created";
            TempData["Id"] = jiraResponse.Id;
            TempData["Key"] = jiraResponse.Key;
            TempData["Self"] = jiraResponse.Self;             

            return RedirectToAction("Index", "Home");
        }
    }

    [HttpGet]
    public async Task<ActionResult> GetUserToAssign()
    {

        using (var httpClient = new HttpClient())
        {
            var formatters = new List<MediaTypeFormatter>() {
            new JsonMediaTypeFormatter(),
            new XmlMediaTypeFormatter()
                };
            httpClient.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue(
                    "Basic", Convert.ToBase64String(
                        System.Text.ASCIIEncoding.ASCII.GetBytes(
                           $"login:password"))); 
            var httpRequestMessage = new HttpRequestMessage();
            httpRequestMessage.Method = HttpMethod.Get;
            var content = await httpClient.GetAsync("<company>atlassian.net/rest/api/2/user/assignable/search?project=HOP");               

            string responseBody = await content.Content.ReadAsStringAsync();
            var assigneBodyResponse = new List<AssigneeRequestBody>();
            var allUsersFromJira = await content.Content.ReadAsAsync<IEnumerable<AssigneeRequestBody>>(formatters);

            var resultsJira = allUsersFromJira.Cast<AssigneeRequestBody>().ToList();

            return View();
        }

Home Controller

 public ActionResult Index(LogFilterModelVm filterModel)
    {           
        if (filterModel == null || filterModel.ResultCount == 0)
        {
            filterModel = new LogFilterModelVm() { CurrentPage = 0, ResultCount = 50, FromDate = DateTime.Now.AddDays(-7), ToDate = DateTime.Now };
        }
        using (var repositoryCollection = new repositoryCollection())
        {

            var logsFromDb = repositoryCollection.ErrorLogsRepository.AllErrorLogs(filterModel.CurrentPage, filterModel.ResultCount, filterModel.Filter_Source, filterModel.Filter_Type, filterModel.Filter_User, filterModel.Filter_Host, filterModel.Filter_SearchBar, filterModel.FromDate , filterModel.ToDate);

            var chartCount = new List<int>();
            var chartNames = new List<string>();
            foreach(var item in logsFromDb.ChartData)
            {
                chartCount.Add(item.Count);
                chartNames.Add(item.Source);
            }

            var viewModel = new LogPackageVm()
            {
                ChartCount = chartCount,
                ChartNames = chartNames,
                LogItems = logsFromDb.LogItems,
                FilterModel = new LogFilterModelVm(),
                Distinct_SourceLog = logsFromDb.Distinct_SourceLog,
                Distinct_TypeLog = logsFromDb.Distinct_TypeLog,
                Distinct_UserLog = logsFromDb.Distinct_UserLog,
                Distinct_HostLog = logsFromDb.Distinct_HostLog,
                Filter_SearchBar = logsFromDb.Filter_SearchBar,
            };

                return View(viewModel);
        }
    }

I have tried to return Get results to View Model but I have failed.

在此处输入图像描述

Above picture shows what is my expected result

Thanks to user @codein I have manage to do this.

I have call the Method within my HomeController

var users = await new TicketController().GetUserToAssign();

Created a ViewBag with SelectList

ViewBag.Users = new SelectList(users, "accountId", "displayName");

And called it on my View

@Html.DropDownListFor(m => model.fields.assignee.name, (IEnumerable<SelectListItem>)ViewBag.Users)

That works great for me.

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