首页 > 解决方案 > 将下拉值从字符串转换为 int

问题描述

我有 C# 中带有 MVC 的 DropDownList 的代码。并且它的值作为字符串传递。但是,我希望它是一个整数。我应该如何在控制器上转换它SaveChanges(),因为它会引发错误。

这是我的查看代码:

<div class="form-group">
    @Html.LabelFor(model => model.DesignationID, "DesignationID", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("DesignationID", new SelectList(ViewBag.Designationid, "Value", "text"),"Select Designation", htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.DesignationID, "", new { @class = "text-danger" })
    </div>
</div>

<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <input type="submit" value="Create" class="btn btn-default" />
    </div>
</div>

这是我的控制器代码:

// POST: Employee/Create
[HttpPost]
public ActionResult Create(Employee employee)
{
    try
    {
        employeeService.Insert(employee);
        unitOfWork.SaveChanges();
        return RedirectToAction("Index");
    }
    catch (Exception ex)
    {
        return View(ex);
    }
}

这是错误:

传入字典的模型项的类型为“System.Data.Entity.Infrastructure.DbUpdateException”,但此字典需要“Pal.Entities.Models.Employee”类型的模型项。

请帮我解决这个问题。

标签: c#asp.net-mvc-5

解决方案


有两件事发生:

  1. 你得到一个DbUpdateException(原因至今未知)。
  2. 它进入catch,您似乎试图通过调用来显示异常return View(ex),但要使其正常工作,视图Create.cshtml需要包含类似@model System.Exception. 事实并非如此,导致另一个异常。
    您需要找到另一种处理异常信息的方法;例如调用它,或创建一个使用Logger.Log(ex)的错误视图,然后通过在 catch-part 中调用该视图。Views/Shared/Error.cshtml@model System.Exceptionreturn View("Error", ex);

推荐阅读