无法编辑主键

时间:2014-07-21 13:46:56

标签: c# sql entity-framework razor asp.net-mvc-5

我正在使用MVC和ASP.NET在c#中创建一个应用程序。我有一个Year实体,它是一个年份表和一个主要ID,称为YearID。当我去编辑YearID时,它不会改变。你能不能编辑主键?有没有什么办法解决这一问题? YearID必须是主键。

控制器代码:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="YearID")] Year year)
{
    try
    {
        if(ModelState.IsValid)
        {
            db.Entry(year).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    }
    catch (DataException /* dex */)
    {
        //Log the error (uncomment dex variable name and add a line here to write a log.
        ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
    }
    return View(year);
}

年份模特:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;

namespace Utility.Models
{
    public class Year
    {
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int YearID { get; set; }

        public virtual ICollection<Week> Weeks { get; set; }
    }
}

编辑html:     @model Utility.Models.Year

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>


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

    <div class="form-horizontal">
        <h4>Year</h4>
        <hr />
        @Html.ValidationSummary(true)
        @Html.HiddenFor(model => model.YearID)

        <div class="form-group">
            @Html.LabelFor(model => model.YearID, new { @class = "control-label col-md-2"             })
            <div class="col-md-10">
                @Html.EditorFor(model => model.YearID)
                @Html.ValidationMessageFor(model => model.YearID)
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

如果需要更多代码,请告诉我。

0 个答案:

没有答案