c# - 将下拉值从字符串转换为 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”类型的模型项。
请帮我解决这个问题。
解决方案
有两件事发生:
- 你得到一个
DbUpdateException
(原因至今未知)。 - 它进入
catch
,您似乎试图通过调用来显示异常return View(ex)
,但要使其正常工作,视图Create.cshtml
需要包含类似@model System.Exception
. 事实并非如此,导致另一个异常。
您需要找到另一种处理异常信息的方法;例如调用它,或创建一个使用Logger.Log(ex)
的错误视图,然后通过在 catch-part 中调用该视图。Views/Shared/Error.cshtml
@model System.Exception
return View("Error", ex);
推荐阅读
- python - 将字符串变量或字符串数组从 python 传递到 curl 脚本
- terraform - Terraform 中的 Prometheus 配置和部署
- google-bigquery - 如何修复 BigQuery 中对更新计划查询的临时中断访问?
- javascript - 使用 google book api (vanilla js) 获取缩略图的问题
- python - Tensorbaord中每个时间步长的线图?
- java - Setter 没有按照应有的方式在 SpringBoot 项目中保存变量
- macos - 在 MacOS/Metal(英特尔 CPU、离散和内部 GPU)上渲染时,帧率会经常下降
- python - 图像处理中的多线程 - 视频 python opencv
- python - 从 numpy ndarray 索引多个最小值
- json - 如何使用 HTTPie 发送嵌套 JSON 的 POST 请求?