C#MVC3模型无效

时间:2012-08-09 08:27:16

标签: c# asp.net-mvc razor model

我目前在模型中遇到错误,说它无法从String转换为Model。 一旦我尝试添加新的数据库表条目,就会发生这种情况。我正在使用SQL Server,而对于前端我正在使用c#mvc3 razor视图。

型号:

    namespace NBProfiler.Model
{
    using System;
    using System.Collections.Generic;

    public partial class PersonContempancy
    {
        public int Id { get; set; }
        public int PersonId { get; set; }
        public Nullable<System.DateTime> AttainedDate { get; set; }
        public int FrameworkId { get; set; }
        public int ContempancyCategoryId { get; set; }
        public int ContempancyId { get; set; }
        public int ContempancyLevelId { get; set; }
        public int FrameworkLevelId { get; set; }

        public virtual Contempancy Contempancy { get; set; }
        public virtual ContempancyCategory ContempancyCategory { get; set; }
        public virtual FrameworkLevel FrameworkLevel { get; set; }
        public virtual Framework Framework { get; set; }
        public virtual Person Person { get; set; }
        public virtual ContempancyLevel ContempancyLevel { get; set; }
    }
}

控制器:

public ActionResult Create()
    {

       ViewBag.Contepancies = db.Contempancies.ToList();
       ViewBag.ContempancyCategory = db.ContempancyCategories.ToList();
       ViewBag.ContempancyLevel = db.ContempancyLevels.ToList();
       ViewBag.FrameworkLevel = db.FrameworkLevels.ToList() ;
       ViewBag.Person = db.People.ToList();
       ViewBag.Framework = db.Frameworks.ToList();

        return View();
    } 

    //
    // POST: /Mapping/Create

    [HttpPost]
    public ActionResult Create(PersonContempancy personcontempancy)
    {

        if (ModelState.IsValid)
        {
            db.PersonContempancies.Add(personcontempancy);
            db.SaveChanges();

            return RedirectToAction("Index");  
        }



        ViewBag.Contepancies = db.Contempancies.ToList();
        ViewBag.ContempancyCategory = db.ContempancyCategories.ToList();
        ViewBag.ContempancyLevel = db.ContempancyLevels.ToList();
        ViewBag.FrameworkLevel = db.FrameworkLevels.ToList();
        ViewBag.Person = db.People.ToList();
        ViewBag.Framework = db.Frameworks.ToList();

        return View(personcontempancy);
    }

最后查看:(我已从视图中删除了其他项目,因为它们都是相同的代码,所以要在此处缩短它我删除它)

    @model NBProfiler.Model.PersonContempancy


@{
    ViewBag.Title = "Create";
}

<h2>Map Skill to Person</h2>


<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
 <link href="../../Content/themes/start/jquery-ui-1.8.22.custom.css" rel="stylesheet"
        type="text/css" />
<script src="../../Scripts/jquery-ui-1.8.11.min.js" type="text/javascript"></script>   

@using (Html.BeginForm()) { 

    @Html.ValidationSummary(true)
    <fieldset>
        <legend>PersonContempancy</legend>

        <div class="editor-label">
           Name:
        </div>
        <div class="editor-field">

            Html.DropDownListFor(m => m.Person, new SelectList(ViewBag.Person as System.Collections.IEnumerable, "PersonId", "PersonName"), "Choose Name")

        </div>

        @*<div class="editor-field">*@
        <div class="editor-label">
                @*@Html.LabelFor(m => m.ContempancyCategory)*@
            </div>
        <div class="editor-field">
            @Html.DropDownListFor(m => m.ContempancyCategory, new   SelectList(ViewBag.ContempancyCategory as System.Collections.IEnumerable, "ContempancyCategoryId", "ContempancyCategoryName"),"Select", new {id = "category" })

        <p>
            <input name="submit" type="submit" value="Map Skill" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Show Table", "Index")
</div>

<script type="text/javascript">
      $(document).ready(function () {
      $("#category").change(function () {
      var idCat = $(this).val();
      $.getJSON("/Mapping/contempancies", { CategoryID: idCat },
      function (MyData) {
      var select = $("#contempancy");
      select.empty();
      $.each(MyData,function(index, itemData) {
      select.append($('<option/>', {
      value: itemData.Value,
      text: itemData.Text
      }));
      });
      });
      });
});
</script>

谢谢!

1 个答案:

答案 0 :(得分:0)

看起来问题是您将视图模型视为实体模型,这绝不是一个好主意。

向/从视图传递数据时,您应该具有显式视图模型,并且只传递视图所需的数据。此外,您将数据层与您的视图耦合,这违背了MVC的目的!

在您的示例中,如果PersonContempancy确实是视图模型(而不是实体),那么您应该使用它来创建映射所需数据的新实体,AutoMapper是一个非常漂亮的库对于那种事情。

public class PersonContempancyViewModel
{
    // update with properties the view needs
}

[HttpPost] 
public ActionResult Create(PersonContempancyViewModel viewModel) 
{ 
    if (ModelState.IsValid) 
    {
        var entity = new PersonContempancyEntity();
        // map properties from view model to entity
        // entity.FrameworkId = viewModel.FrameworkId etc..
        db.PersonContempancies.Add(entity);  
        db.SaveChanges(); 

        return RedirectToAction("Index");   
    }

    ...
}