使用来自 HttpGet 方法的数据填充 Html.BeginForm 下拉列表

Populating Html.BeginForm drop down with data from HttpGet method

我正在使用 Jira Rest Api,我正在尝试创建一个表单,其中包含来自某个项目的所有用户的下拉列表,因此我可以在创建工单时分配他们。

我的表单有效但不幸的是,目前必须对用户进行硬编码。

我是一名新手程序员,我的问题从这里开始:我使用 HttpPost 提交表单并将该值传递给 Api,但在我这样做之前,我需要执行 HttpGet 来填充其中一个表单下拉菜单。这让我感到困惑,我无法做到这一点。

我的表单

                @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>
                }

票务管理员

  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();
        }

家庭控制器

 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);
        }
    }

我已经尝试 return 获取结果以查看模型,但我失败了。

上图是我的预期结果

感谢用户@codein,我已经做到了。

我已经在 HomeController 中调用了方法

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

使用 SelectList 创建了一个 ViewBag

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

并在我的视图中调用它

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

这很适合我。