asp.net mvc4一对多关系数据更新

时间:2015-08-31 11:57:14

标签: asp.net-mvc entity-framework asp.net-mvc-4 one-to-many

我正在尝试更新ilce实体。我可以更新除il信息之外的所有信息吗?你知道为什么会这样吗。

我的模特是:

public class il
{
    public int Id { get; set; }
    public string ad { get; set; }
    public virtual ICollection<ilce> ilce { get; set; }
}

public class ilce
{
    public int Id { get; set; }
    public string ad { get; set; }
    public virtual il il { get; set; }
}

viev:

 @using (Html.BeginForm()) {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)

    <fieldset>
        <legend>ilce</legend>
        @Html.HiddenFor(model => model.Id)

        <div class="editor-label">
            @Html.LabelFor(model => model.ad)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ad)
            @Html.ValidationMessageFor(model => model.ad)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(q=> q.il.Id, new SelectList((System.Collections.IEnumerable)ViewData["iller"], "Id", "ad"))
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

和控制器:

public ActionResult edit(int id)
    {
        ViewData["iller"] = db.il.ToList();
        return View(db.ilce.Where(q=> q.Id == id).FirstOrDefault());
    }
    [HttpPost]
    public ActionResult edit(ilce ilce)
    {
        il il = db.il.Find(ilce.il.Id);
        ilce.il = il;
        try
        {
            db.Entry(ilce).State = EntityState.Modified;
            db.SaveChanges();
            ViewBag.mesaj = "done!";
        }
        catch (Exception)
        {
            ViewBag.mesaj = "error";
            throw;
        }
        ViewData["iller"] = db.il.ToList();
        return View(ilce);
    }

如果您愿意,我可以将此项目发送给您。

0 个答案:

没有答案