Witam,
mam problem z DropDownListFor, wyrzucami mi wyjątek NullReferenceException, próbowałem różnych kombinacji kodu znalieżionych w sieci, ale zawsze jest to samo.
Models:
public class Category
{
[Key]
[ScaffoldColumn(false)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CategoryId { get; set; }
[Required]
[Display(Name = "Nazwa kategorii: ")]
public string Name { get; set; }
public virtual List<Word> Words { get; set; }
[ScaffoldColumn(false)]
public string UserEmail { get; set; }
public virtual User User { get; set; }
}
public class User
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[ScaffoldColumn(false)]
public int UserId { get; set; }
[Key]
[Required]
[EmailAddress]
[StringLength(100)]
[Display(Name = "Adres Email: ")]
public string Email { get; set; }
[Required]
[Display(Name = "Hasło: ")]
public string EncryptedPassword { get; set; }
[ScaffoldColumn(false)]
public string PasswordSalt { get; set; }
[NotMapped]
public string Password { get; set; }
public virtual List<Word> Words { get; set; }
public virtual List<Category> Categorys { get; set; }
}
public class Word
{
[Key]
[ScaffoldColumn(false)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int WordId { get; set; }
[Required]
[Display(Name = "Polskie słowo: ")]
public string PolishWord { get; set; }
[Required]
[Display(Name = "Angielskie słowo: ")]
public string EnglishWord { get; set; }
[Required]
public string Status { get; set; }
[ScaffoldColumn(false)]
public string UserEmail { get; set; }
public virtual User User { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
}
public class WordCategory
{
public List<Category> category { get; set; }
public Word word { get; set; }
}
Controller:
public ActionResult CreateWord()
{
using (var db = new UserContext())
{
WordCategory wordCategory = new WordCategory();
var categorys = db.Categorys.Where(c => c.UserEmail == UserController.ActualyLoggedUser.Email).ToList();
var newWord = new Word();
wordCategory.category = categorys;
wordCategory.word = newWord;
return View(wordCategory);
}
}
View:
<div class="form-group">
@Html.LabelFor(model => model.word.Category, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model=>model.word.CategoryId, new SelectList(Model.category, "CategoryId", "Name")) //w tej linijce wyrzuca wyjątek
@Html.ValidationMessageFor(model => model.word.Category.Name)
</div>
</div>