0

Good afternoon, My question is a bit mixed up. I have two objects, one depends on the other one to be created. Object #1 is "Local" and object #2 is "NotasAdjuntas". To create a "NotasAdjuntas" I need to know which "Local" it belongs to.

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

}

My Issue is when I try to edit "notasAdjuntas", I get an error that says that the field "Local" is requiered, so it doesn't validate the model. The only things I want to edit are the Asunto and Detalle. Fecha and Hora need to stay the same.

this is my view for edit:

 @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`
}

these are the edit methods:

 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();
        }

Thanks for your help!

Syrup72
  • 116
  • 1
  • 12
  • [ViewModels](https://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) avoid situations like this. You can then have validation rules for your form model (Asunto, Detalle) which will differ from your database model (required Fecha, Hora). – Jasen Sep 21 '17 at 20:31
  • I added a ViewModel but I'm still getting the same error, the field "Local" is requiered. – Syrup72 Sep 22 '17 at 17:48
  • Your ViewModel would only contain the properties you want to edit. I understand you do not want to edit `Local` so you leave this out of the view model or remove the Required attribute. In the edit action you will use the view model to query the matching entity and update its fields. `ModelState.IsValid` should pass because you should be validating the ViewModel without the Required attribute. – Jasen Sep 22 '17 at 17:52
  • Thanks for your help! I created the viewModel with the specific atributes that i wanted. Without having to validate everything from the model. – Syrup72 Sep 22 '17 at 18:48

0 Answers0