Tushar
Tushar

Reputation: 1

Convert Dropdown value from string to int

I have code for a DropDownList in C# with MVC. And the value of that is passed as a string. But, I want that as an integer. How should I convert it on the controller before SaveChanges(), because it is throwing an error.

Here is my View code:

<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>

Here is my Controller code:

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

Here is the error:

The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbUpdateException', but this dictionary requires a model item of type 'Pal.Entities.Models.Employee'.

Please help me to resolve this.

Upvotes: 0

Views: 124

Answers (1)

Peter B
Peter B

Reputation: 24232

There are two things going on:

  1. You are getting a DbUpdateException (for reasons so far unknown).
  2. It goes into the catch, where you appear to be trying to show the Exception by calling return View(ex), but for that to work the View Create.cshtml would need to contain something like @model System.Exception. That isn't the case, causing yet another Exception.
    You need to find another way to deal with the Exception info; e.g. call Logger.Log(ex) on it, or create an error view Views/Shared/Error.cshtml that uses @model System.Exception, and then call that View by doing return View("Error", ex); in the catch-part.

Upvotes: 1

Related Questions