【问题标题】:Populating Html.BeginForm drop down with data from HttpGet method使用来自 HttpGet 方法的数据填充 Html.BeginForm 下拉列表
【发布时间】:2019-09-23 12:39:19
【问题描述】:

我正在使用 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);
        }
    }

我尝试将 Get 结果返回给 View Model,但失败了。

上图显示了我的预期结果

【问题讨论】:

  • 你试过什么?显示您的视图的实现
  • 我已经编辑了我的帖子。谢谢
  • 您需要从您的 Get 方法(即 resultsJira)分配结果以查看数据,然后使用它来填充您的下拉列表。类似于 ViewBag.Users = new SelectList(resultsJira ,"dataValueField","dataTextField") 其中 dataValue 和 dataText 是数据源的属性。然后在您看来,只需使用 @Html.DropDownlist("Users")
  • 但是我如何确保这个方法(Get)在页面加载时执行?编辑:当我现在运行它时,我发现没有 viewData("User") 我如何确保这个 Get 在页面加载时执行?
  • 您可以将 Get 方法的返回类型更改为 Task> 并在 Index 操作中调用它,如下所示: var users = await GetUserToAssign() 。并按照前面的建议使用结果来实现 selectList。您需要使索引操作异步。

标签: c# api model-view-controller jira


【解决方案1】:

感谢用户@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)

这对我很有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2020-09-24
    • 2020-09-22
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多