【问题标题】:Posting DropDownList Value to MVC Controller将 DropDownList 值发布到 MVC 控制器
【发布时间】:2012-10-04 13:41:50
【问题描述】:

我正在尝试从 DropDownList 获取信息并将 SelectListItem“值”发布到控制器中的另一个 ActionResult 方法。它将被传递给的控制器将采用一个整数值并在另一个查询中使用它。

我的控制器填充 DropDownList 的方法如下:

public ActionResult SelectCategory()
{
    var model = new TestTypesViewModel();

    var query = (from ab in db.Tbl_Admin_Batch
                 from ub in db.Tbl_Admin_User_Batch
                 where ub.User_Id == 45875 && ab.Batch_Id == ub.Batch_Id
                select ab).ToList();

    model.Test_Types = query.Select(c => new SelectListItem
        {
            Text = c.Batch_Name,
            Value = c.Batch_Id.ToString()
        }).ToList();

   return View(model);

我的 TestTypesViewModel 的 ViewModel 如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HFI_Assessment_Administration.ViewModels
{
    public class TestTypesViewModel
    {
        public int Batch_ID { get; set; }
        public string Test_Type { get; set; }

        public IEnumerable<SelectListItem> Test_Types { get; set; }
    }
}

我是 MVC 的新手,并试图保持简单,我知道 Batch_ID 和 Test_Type 尚未指定,但我不确定此时它们是否有必要。

任何建议或帮助将不胜感激,非常感谢!

编辑:

我现在有一个 SelectCategory 的视图,如下所示:

@model HFI_Assessment_Administration.ViewModels.TestTypesViewModel

@{
    ViewBag.Title = "SelectCategory";
}

@using (Html.BeginForm("Practice", "WebFormUserList"))
{
    @Html.DropDownListFor(x => x.Batch_ID, Model.Test_Types)
    <input type="submit" />
} 

它被传递到的控制器如下:

[HttpPost]
public ActionResult Practice(TestTypesViewModel model, int Parent_ID = 45875)
{
    var query = (from u in db.Users
                 join ur in db.User_Relationship on u.User_ID equals ur.Child_ID
                 join ub in db.Tbl_Admin_User_Batch on u.User_ID equals ub.User_Id

                 join ut in db.User_Tests on u.User_ID equals ut.User_ID into ps
                 from ut in ps.DefaultIfEmpty()

                 join lu in db.Lookups on u.First_LanguageID equals lu.LookupID

                 where ur.Parent_ID == Parent_ID && ub.Batch_Id == model.Batch_ID

                 group new { u, lu, ut } by new
                 {
                     u.User_ID,
                     u.Forename,
                     u.Surname,
                     u.Client_Code,
                     u.User_Name,
                     u.Password,
                     u.Email,
                     u.Gender,
                     u.Report_date,
                     u.EmailDate,
                     u.Job_Function,
                     lu.LookupValue
                 } into g

                 select new UserViewModel
                    {
                         User_ID = g.Key.User_ID,
                         Forename = g.Key.Forename,
                         Surname = g.Key.Surname,
                         Client_Code = g.Key.Client_Code,
                         User_Name = g.Key.User_Name,
                         Password = g.Key.Password,
                         Email = g.Key.Email,
                         Gender = g.Key.Gender,
                         Report_Date = g.Key.Report_date,
                         Email_Date = g.Key.EmailDate,
                         Test_Count = g.Count(p => p.ut.Test_ID != null),
                         Test_Completed = g.Count(p => p.ut.Completed != null),
                         Job_Function = g.Key.Job_Function,
                         Lookup_Value = g.Key.LookupValue
                     }).ToList();

        return View(query);
    }

实践观如下:

@model IEnumerable<HFI_Assessment_Administration.ViewModels.UserViewModel>

@{
    ViewBag.Title = "ChildUsers";
}

<h2>Practice</h2>

<div>
    @{
        var grid = new WebGrid(Model);
    }

    @grid.GetHtml(

    tableStyle: "webgrid",
    headerStyle: "webgrid-header",
    footerStyle: "webgrid-footer",
    alternatingRowStyle: "webgrid-alternating-row",  
    selectedRowStyle: "webgrid-selected-row",
    rowStyle: "webgrid-row-style",

    columns: grid.Columns
    (
        grid.Column(columnName:"User_ID", header: "User ID", style: "text-align-center"),
        grid.Column(columnName:"Forename", header: "Forename", style: "text-align-center"),
        grid.Column(columnName:"Surname", header: "Surname", style: "text-align-center"),
        grid.Column(columnName:"Client_Code", header: "Client Code", style: "text-align-center"),
        grid.Column(columnName:"User_Name", header: "User Name", style: "text-align-center"),
        grid.Column(columnName:"Password", header: "Password", style: "text-align-center"),
        grid.Column(columnName:"Email", header: "Email", style: "text-align-center"),
        grid.Column(columnName:"Gender", header: "Gender", style: "text-align-center"),
        grid.Column(columnName:"Report_Date", header: "Report Date", style: "text-align-center"),
        grid.Column(columnName:"Email_Date", header: "Email Date", style: "text-align-center"),
        grid.Column(columnName:"Test_Count", header: "Count", style: "text-align-center"),
        grid.Column(columnName:"Test_Completed", header: "Completed", style: "text-align-center"),
        grid.Column(columnName:"Job_Function", header: "Job Function", style: "text-align-center"),
        grid.Column(columnName:"Lookup_Value", header: "Language", style: "text-align-center")
        )          
    )
</div>

在我尝试转到网格的下一页或尝试对网格进行排序之前,一切都很好。在我得到错误的地方,“/”应用程序中的服务器错误。找不到资源。

【问题讨论】:

    标签: post asp.net-mvc-4 viewmodel html-select selectlistitem


    【解决方案1】:

    有很多方法可以实现这一目标。您可以使用标准的 &lt;form&gt; 标签或使用 AJAX 发送值。

    我们来看第一种情况:

    @model TestTypesViewModel
    @using (Html.BeginForm("SomeAction", "SomeController"))
    {
        @Html.DropDownListFor(x => x.Test_Type, Model.Test_Types)
        <button type="submit">OK</button>
    }
    

    现在在您的目标操作中:

    [HttpPost]
    public ActionResult SomeAction(TestTypesViewModel model) 
    {
        // model.Test_Type will contain the selected value here
    
        // Notice that if you intend to return the same view as the GET action 
        // (SelectCategory.cshtml) you should assign the Test_Types property on
        // your model by querying your database the same way you did in the GET action
        // before passing this model to the view. If on the other hand you intend to
        // redirect here you don't need to assign it.
    }
    

    第二种可能性是使用 AJAX。因此,例如,您可以为下拉列表提供一个 id 并有一些链接,单击该链接将调用目标控制器操作,使用 AJAX 向其发送选定的值:

    @Html.DropDownListFor(x => x.Test_Type, Model.Test_Types, new { id = "testTypeDdl" })
    @Html.ActionLink("click me", "SomeAction", null, new { id = "myLink" })
    

    然后当点击某个按钮或链接时,使用$.ajax 请求:

    $(function() {
        $('#myLink').click(function() {
            $.ajax({
                url: this.href,
                type: 'GET',
                cache: false,
                data: { selectedValue: $('#testTypeDdl').val() },
                success: function(result) {
                    alert('The value was submitted to the server');
                }
            });
            return false;
        });
    });
    

    现在您的控制器操作可能具有以下签名:

    public ActionResult SomeAction(string selectedValue)
    {
        // Process the selected value here and return some result.
        // This result could either be a PartialView or a JsonResult
        // depending on your requirements.
    }
    

    【讨论】:

    • 哇,感谢您的快速响应,我现在就试一试,看看我能得到什么!
    • 一个简单的问题,您的评论是什么意思: // 请注意,如果您打算返回与 GET 操作相同的视图 // (SelectCategory.cshtml),您应该将 Test_Types 属性分配给// 在将模型传递给视图之前,通过与 GET 操作中相同的方式查询数据库来创建模型。另一方面,如果您打算 // 重定向到这里,则不需要分配它。
    • 我的意思是,如果您在 POST 操作中return View(model);,您需要像在 GET 操作中一样为 model.Test_Types = ... 赋值。
    猜你喜欢
    • 2021-11-09
    • 2017-01-01
    • 1970-01-01
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 2022-11-05
    • 1970-01-01
    • 2017-06-22
    相关资源
    最近更新 更多