gpt4 book ai didi

c# - 在 asp.net MVC 中使用下拉列表进行搜索

转载 作者:行者123 更新时间:2023-11-30 15:26:00 24 4
gpt4 key购买 nike

我是 ASP.NET MVC 的新手。我想使用下拉列表中的选定项目来搜索我的数据库表。下拉列表是从自动绑定(bind)到 View 的 BOL 模型生成的。

下面是我的代码片段

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

namespace DentiCareApp.Areas.Admin.Controllers
{
[AllowAnonymous]
public class GenerateInvoiceController : Controller
{
private TreatmentBs objBs;

public GenerateInvoiceController()
{
objBs = new TreatmentBs();
}
// GET: Admin/GenerateInvoice
public ActionResult Index(string CompanyID)
{
DentiCareEntities db = new DentiCareEntities();
ViewBag.CompanyId = new SelectList(db.Companies, "CompanyId", "CompanyName");

if (CompanyID == null)
{
return View();
}
else
{
return View(db.Treatments.Where(x => x.Company == CompanyID.Take(50)));
}
//return View();
}

下面也是view的界面。

enter image description here

其次,我还希望搜索结果出现在同一页面上。我该怎么做呢?如果我为此创建一个单独的操作,我将需要为其创建一个单独的 View 。可以使用局部 View 吗?如果是怎么办?

下面是 View 的代码

    @model BOL.GenerateInvoice
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<p></p>
<p></p>
<p></p>
<h2>Quickly Generate Invoice</h2>
@using (Html.BeginForm("Index", "GenerateInvoice", FormMethod.Get))
{
@Html.AntiForgeryToken()
<div class="">
<div>
@Html.DropDownList("MyCompany.CompanyId", (IEnumerable<SelectListItem>)ViewBag.CompanyId, "Select Company", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.MyCompany.CompanyId, "", new { @class = "text-danger" })
<input type="submit" value="Search" class="btn btn-primary" />
</div>
</div>
}

最佳答案

试试这个。

Controller 操作:

public ActionResult Index(string CompanyID)
{
DentiCareEntities db = new DentiCareEntities();
ViewBag.CompanyId = new SelectList(db.Companies, "CompanyId", "CompanyName", CompanyID); // preselect item in selectlist by CompanyID param

if (!String.IsNullOrWhiteSpace(CompanyID))
{
return View();
}

return View(db.Treatments.Where(x => x.CompanyID == CompanyID).Take(50));
}

查看代码:

@model IEnumerable<Treatment>

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Quickly Generate Invoice</h2>

@using (Html.BeginForm("Index", "GenerateInvoice", FormMethod.Get))
{
@Html.AntiForgeryToken()

@Html.DropDownList("CompanyId", (SelectList)ViewBag.CompanyId, "Select Company", new { @class = "form-control" })
<input type="submit" value="Search" class="btn btn-primary" />
}

@if(Model != null && Model.Any())
{
foreach(var item in Model)
{
@Html.DisplayFor(model => item)
}
}

您可以在此处更改 DisplayFor() 以显示给定 Treatment 的各个属性,例如 @Html.DisplayFor(model => model.TreatmentID)

关于c# - 在 asp.net MVC 中使用下拉列表进行搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30125142/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com