【问题标题】:how to select dropdownlist value and display in mvc3?如何选择下拉列表值并在 mvc3 中显示?
【发布时间】:2025-12-25 12:00:11
【问题描述】:

我有一个 MVC3 Web 应用程序。在index.cshtml 我有两个下拉列表。当我从这些列表中选择时,我需要单击 next 按钮,并且我想显示选定的值。我该怎么做?

homecontroller.cs

DataRepository objRepository = new DataRepository();

public ActionResult Index()
{
    ViewModel objViewModel = new ViewModel();
    objViewModel.ID = objRepository.GetPricingSecurityID();
    objViewModel.ddlId = objRepository.GetCUSIP();
    return View(objViewModel);
}

ViewModel.cs

public class ViewModel
{
    //DDL ID
    [Required(ErrorMessage = "Please select a PricingSecurityID")]
    public List<SelectListItem> ddlId { get; set; }

    //DropDownList Values
    [Required(ErrorMessage = "Please select a PricingSecurityID")]
    public List<SelectListItem> ID { get; set; }
}

index.cshtml

<div class="editor-label">
    @Html.Label("Pricing SecurityID")
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.ID,
        new SelectList(Model.ID, "Value", "Text"),
        "-- Select category --"
    )
    @Html.ValidationMessageFor(model => model.ID)
</div>

<div class="editor-label">
    @Html.Label("CUSIP ID")
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.ddlId,
        new SelectList(Model.ddlId, "Value", "Text"),
        "-- Select category --"
    )
    @Html.ValidationMessageFor(model => model.ddlId)
</div>
<p>
    <input type="submit" value="Next" />
</p>

如何显示选定的值?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 model-view-controller


    【解决方案1】:

    如果您的要求是构建某种向导,则需要一种在步骤之间维护状态的方法。

    ViewBag 对此没有好处,因为您应该在每个向导步骤中遵循 PRG(发布/重定向/获取)模式。

    TempData 可用于在步骤之间向前导航,但如果用户返回或直接导航到某个步骤,则会翻倒。

    因此,您需要寿命更长的东西。 ASP.NET Session 对象或数据库都是很好的候选对象。

    这是一个例子:

    public class WizardController : Controller
    {
        public ActionResult Step1()
        {
            var session = GetWizardSession();
    
            if (session.Step1 == null)
            {
                session.Step1 = new Step1View
                {
                    PricingSecurityIds = new SelectList(new[] { 1, 2, 3, 4, 5 }),
                    SomeOtherIds = new SelectList(new[] { 1, 2, 3, 4, 5 })
                };
            }
    
            return View(session.Step1);
        }
    
        [HttpPost]
        public ActionResult Step1(Step1View cmd)
        {
            var session = GetWizardSession();
    
            // save the wizard state
            session.Step1.SelectedPricingSecurityId = cmd.SelectedPricingSecurityId;
            session.Step1.SelectedSomeOtherId = cmd.SelectedSomeOtherId;
    
            // now onto step 2
            session.Step2 = new Step2View
            {
                PricingSecurityId = cmd.SelectedPricingSecurityId,
                SomeOtherId = cmd.SelectedSomeOtherId,
                Name = "John Smith"
            };
    
            return RedirectToAction("step2");
        }
    
        public ActionResult Step2()
        {
    
            return View(GetWizardSession().Step2);
        }
    
        public WizardSession GetWizardSession()
        {
            var session = Session["wizardsession"];
    
            if (session == null)
            {
                session = new WizardSession();
                Session["wizardsession"] = session;
            }
    
            return session as WizardSession;
        }
    }
    
    public class Step1View
    {
        public SelectList PricingSecurityIds { get; set; }
        public SelectList SomeOtherIds { get; set; }
        public int SelectedPricingSecurityId { get; set; }
        public int SelectedSomeOtherId { get; set; }
    }
    
    public class Step2View
    {
        public int PricingSecurityId { get; set; }
        public int SomeOtherId { get; set; }
        public string Name { get; set; }
    }
    
    public class WizardSession
    {
        public Step1View Step1 { get; set; }
        public Step2View Step2 { get; set; }
    }
    
    • Step1中,我们调用GetWizardSession。这会从 ASP.NET Session 返回一个对象,其中包含我们为向导中的每个步骤收集的所有信息。在此示例中,我们只是存储每个步骤的 ViewModel(即session.Step1)。
    • 我们检查会话中是否存在 Step1,如果不存在则创建它。然后我们将 Step1 模型传递给我们的视图。
    • 当用户提交表单时,我们会更新session.Step1 中的“选定”值。这确保如果用户导航回 /step1,我们“记住”他们的值。然后,我们为 Step2 构建模型并将其保存在会话中。
    • 当我们导航到 /step2 时,我们假设会话中存在模型(因为它们应该从 step1 到达这里)所以我们只返回 return View(GetWizardSession().Step2);

    意见:

    步骤 1

    @model MvcWizardDemo.Controllers.Step1View
    
    @{
        ViewBag.Title = "Step1";
    }
    
    <h2>Step1</h2>
    
        <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
    
        @using (Html.BeginForm()) {
            @Html.ValidationSummary(true)
            <fieldset>
                <legend>Step1View</legend>
                <div class="editor-label">
                    @Html.LabelFor(m => m.PricingSecurityIds)
                </div>
                <div class="editor-field">
                    @Html.DropDownListFor(m => m.SelectedPricingSecurityId, Model.PricingSecurityIds)
                    @Html.ValidationMessageFor(m => m.PricingSecurityIds)
                </div>
                <div class="editor-label">
                    @Html.LabelFor(m => m.SomeOtherIds)
                </div>
                <div class="editor-field">
                    @Html.DropDownListFor(m => m.SelectedSomeOtherId, Model.SomeOtherIds)
                    @Html.ValidationMessageFor(m => m.SomeOtherIds)
                </div>
                <p>
                    <input type="submit" value="Next" />
                </p>
            </fieldset>
        }
    

    第二步

    @model MvcWizardDemo.Controllers.Step2View
    
    @{
        ViewBag.Title = "Step2";
    }
    
    <h2>Step2</h2>
    
    Hi, @Model.Name you selected the following values in the previous step:
    
    <p>
        <strong>Security Id:</strong> @Model.PricingSecurityId
    </p>
    
    <p>
        <strong>Some other Id:</strong> @Model.SomeOtherId
    </p>
    

    【讨论】:

      【解决方案2】:

      试试这个应该可以的:

      [HttpPost]    
      public ActionResult Index(ViewModel model)
      {
          // put what you want to show
      
      }
      

      【讨论】:

      • 这行不通。您需要向 POST 模型添加其他属性以存储选定的值。根据我的回答。
      最近更新 更多