0

I am using autocomplete from JQueryUIHelpers in my Asp.Net MVC project with EF6.

Model structure:

public class Employee
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string SecondName { get; set; }
    [NotMapped]
    public string FullName => FirstName + " " + SecondName;
    public bool IsDriver { get; set; } = false;
    public virtual ICollection<Delivery> Deliveries { get; set; }
}
public class Delivery
{
    [Key]
    public int Id { get; set; }
    [Required]
    public Employee Driver { get; set; }
    public virtual ICollection<EggsMag> Eggs { get; set; }
}

EmployeeController:

public ActionResult Drivers(string term)
{
    var drivers = _rep.GetAll(e => e.IsDriver && (e.FirstName.StartsWith(term) || e.SecondName.StartsWith(term)));
    return Json((from d in drivers select new { label = d.FullName, value = d.Id }).ToList(), JsonRequestBehavior.AllowGet);
}

DeliveriesController:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,DateOfDelivery,Driver")] Delivery delivery)
{
    if (ModelState.IsValid)
    {
        _rep.Save(delivery);
        return RedirectToAction("Index");
    }  

    return View(delivery);
}

View:

@Html.JQueryUI().AutocompleteFor(m => m.Driver.Id, Url.Action("Drivers", "Employees"), "DriverId", null)

Problem Description:
Autocomplete is working correctly but when in Edit view I send POST request I receive all the data, but ModelState.IsValid is false.
The error shows that fields of FirstName and SecondName are empty which is true because I sent just Id of existing Driver, not whole object.
Is there a way to fix it?
Maybe some way to change validation to not check inner model(Driver) fields except Driver.Id existence.

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
Levvy
  • 1,100
  • 1
  • 10
  • 21
  • 5
    You editing data. Do NOT use data models in your view. Use a view model containing only those properties that are need in the view. [What is ViewModel in MVC?](https://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  Oct 22 '17 at 23:51
  • Data model != viewmodel. Use viewmodel required properties to bind into view and then pass them to controller action method, and assign related data model from viewmodel properties. – Tetsuya Yamamoto Oct 23 '17 at 00:48
  • so I need something like EditDeliveryViewModel.cs? with properties: Delivery and Driver or something else because Driver is already in Delivery? – Levvy Oct 23 '17 at 13:04
  • Your view model needs to contain only the properties you need in the view - e.g `int SelectedDriver` for binding to the autocomplete textbox –  Oct 24 '17 at 05:21
  • Ok. I figured it out. thanks – Levvy Oct 24 '17 at 05:24

0 Answers0