C# 将下拉列表值从字符串转换为int
我有C#和MVC的下拉列表代码。它的值作为字符串传递。但是,我希望它是一个整数。在C# 将下拉列表值从字符串转换为int,c#,asp.net-mvc-5,C#,Asp.net Mvc 5,我有C#和MVC的下拉列表代码。它的值作为字符串传递。但是,我希望它是一个整数。在SaveChanges()之前,我应该如何在控制器上转换它,因为它抛出了一个错误 以下是我的查看代码: <div class="form-group"> @Html.LabelFor(model => model.DesignationID, "DesignationID", htmlAttributes: new { @class = "control-label col-md-2" }
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>
以下是错误:
传递到字典中的模型项的类型为
'System.Data.Entity.Infrastructure.DbUpdateException',但是
字典需要类型为的模型项
“Pal.Entities.Models.Employee”
请帮我解决这个问题。发生了两件事:
DbUpdateException
(原因目前未知)catch
,在那里您似乎试图通过调用返回视图(ex)
来显示异常,但要使其工作,视图Create.cshtml
需要包含类似@model System.Exception
的内容。事实并非如此,这会导致另一个异常。您需要找到另一种方法来处理异常信息;e、 g.在其上调用
Logger.Log(ex)
,或创建一个使用@model System.Exception
的错误视图Views/Shared/error.cshtml
,然后通过执行返回视图(“error”,ex)调用该视图
您是否可以显示您正在插入的员工的实例,即
员工
在尝试存储该员工之前,您可能需要的副本
// POST: Employee/Create
[HttpPost]
public ActionResult Create(Employee employee)
{
try
{
employeeService.Insert(employee);
unitOfWork.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception ex)
{
return View(ex);
}
}