Wednesday 20 September 2017

Searching with a dropdown list in asp.net MVC

Controller action:
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));
}
View code:
@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)
    }
}
You can change the DisplayFor() here to show individual properties of the given Treatment, such as @Html.DisplayFor(model => model.TreatmentID) and such

No comments:

Post a Comment

Note: only a member of this blog may post a comment.

Blog Archive