asp.net mvc显示下拉值

时间:2018-01-22 11:41:49

标签: asp.net-mvc

我通过从数据库中提取数据创建了一个下拉列表。我想在点击提交时显示所选的值。在控制器中,我试图将所选值存储在ViewBag中并显示它。当我调试代码时,我发现viewbag存储了null值。以下行将值存储在viewbag中。

ViewBag.scode = emp.Service_Code;

调试时,Service_Code会显示该值,但会在null中存储为ViewBag。请帮我解决这个问题。

模型

public class Employee
{
    public int Service_Code { get; set; }
    public string Service_Name { get; set; }
    public IEnumerable<SelectListItem>  ser_code { get; set; } 
}

查看

@model mvclearn.Models.Employee
@{
    ViewBag.Title = "menu";
}

<link href="~/Content/bootstrap.css" rel="stylesheet" />
<div class="container">
    @using (Html.BeginForm("save", "Test", FormMethod.Post))
    {
        @Html.DropDownListFor(m => m.Service_Code, Model.ser_code, "--select-",new { @class = "form-control" })
        <input type="submit" value="submit" class="btn-block" />
    }
 </div>
 <div>You entered:@ViewBag.scode</div>

控制器

public ActionResult menu()
{
    RevenueDashboardEntities rdb = new RevenueDashboardEntities(); 
    var model = new Employee()
    {
        ser_code = new SelectList(db.Services, "Service_Code", "Service_Name")    
    };
    return View(model);
}

[HttpPost]
public ActionResult save(Employee emp)
{
    RevenueDashboardEntities rdb = new RevenueDashboardEntities();
    ViewBag.scode = emp.Service_Code;
    return View("menu");   
}

1 个答案:

答案 0 :(得分:3)

所选值已经通过其Service_Code属性中的模型在操作中发布。

您需要的是将模型返回到视图,它将使用在表单帖子中选择的内容填充所选值:

[HttpPost]
public ActionResult save(Employee emp)
{
    RevenueDashboardEntities rdb = new RevenueDashboardEntities();
    // this is needed to populate the items of dropdown list again
    emp.ser_code  = new SelectList(db.Services, "Service_Code", "Service_Name");
    // sending model back to view
    return View("menu",emp);   
}

现在,在发布表单后,页面加载时将自动选择该值,您可以通过写入显示div内页面上的值:

<div>You entered: @Model.Service_Code</div>