下午好,我的问题有些混乱。我有两个对象,一个取决于另一个要创建的对象。对象#1是“本地”,对象#2是“NotasAdjuntas”。要创建“NotasAdjuntas”,我需要知道它属于哪个“本地”。
NotasAdjuntas Class
public class NotasAdjuntas
{
public int Id { get; set; }
[Required]
[MinLength(3)]
[MaxLength(20)]
public string Asunto { get; set; }
[Required]
public string Detalle { get; set; }
[DataType(DataType.Date)]
public DateTime Fecha { get; set; }
[DataType(DataType.Time)]
public DateTime Hora { get; set; }
[Required] //I've added a requiered so when I delete a "Local", it automatically deleted all the "notasAjuntas" that belong to it.
public virtual Local local { get; set; }
public virtual string username { get; set; }
}
我的问题是当我尝试编辑“notasAdjuntas”时,我收到一条错误消息,指出“Local”字段是必需的,因此它不会验证模型。我想编辑的唯一内容是Asunto和Detalle。 Fecha和Hora需要保持不变。
这是我的编辑观点:
@model AutoPlanMCV.Models.NotasAdjuntas
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>NotasAdjuntas</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.Asunto, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Asunto, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Asunto, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Detalle, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Detalle, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Detalle, "", new { @class = "text-danger" })
</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>`enter code here`
}
这些是编辑方法:
public ActionResult Edit(int? id,int localId)
{
Session["LocalIdEditNotasAdjuntas"] = localId;
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
NotasAdjuntas notasAdjuntas = db.Notas.Find(id);
if (notasAdjuntas == null)
{
return HttpNotFound();
}
return View(notasAdjuntas);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(NotasAdjuntas notasAdjuntas)
{
var id = Session["LocalIdEditNotasAdjuntas"].ToString();
int localId = 0;
int.TryParse(id, out localId);
Local local = db.Locales.Find(localId);
notasAdjuntas.local = local;
if (ModelState.IsValid)
{
//db.Entry(notasAdjuntas).State = EntityState.Modified;
NotasAdjuntas original = db.Notas.Find(notasAdjuntas.Id);
original.local = notasAdjuntas.local;
original.Asunto = notasAdjuntas.Asunto;
original.Detalle = notasAdjuntas.Detalle;
original.Id = notasAdjuntas.Id;
db.SaveChanges();
Session["LocalIdEditNotasAdjuntas"] = null;
return RedirectToAction("Details", "Locals", new { id = localId });
}
return View();
}
感谢您的帮助!