Use Jquery Autocomplete in Id properties

Asked

Viewed 185 times

1

I have my Model as follows

public class Album {
   public int Id {get;set;}
   public int ArtistaId {get;set;}
}
public class Artista {
   public int Id {get;set;}
}

And in my view, I use:

  @Html.TextBoxFor(model => model.ArtistaId, new { @class = "form-control" })

Problem:

I wanted to use a AutoComplete, for him to seek and set the ArtistaId. But as he is a "Id", and when filling this TextBox, he informs on ValidationMessage that the field accepts only numerical data

1 answer

1


Autocomplete is correct. The behavior would be right if you were filling the Id in hand, which makes no sense within this context.

Place an uncharted text field in your Model in a database as follows:

public class Album 
{
    [Key]
    public int Id {get;set;}
    public int ArtistaId {get;set;}

    [NotMapped]
    public String NomeArtista { get; set; }

    public virtual Artista Artista { get; set; }
}

View will look like this:

@Html.HiddenFor(model => model.ArtistaId)
@Html.TextBoxFor(model => model.NomeArtista, new { @class = "form-control" })

Put the Autocomplete on NomeArtista, putting in the event success the completion of ArtistaId.

  • 1

    thanks for the answer, good, after much and much reading, I removed the Repospository and service =), and as in this case I have not Viewmodel(removed too) I did not know how to solve. Enjoying, happy new year =)

  • @Rod Viewmodel need not remove. Happy New Year!

  • I only saw utility in Viewmodel, in some models, in many was only "duplication" of code...used Automapper, Now for the Grids return a DTO which is "almost the same thing"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.