1

I got a project where i can insert news into a database with ASP.NET MVC. What i have is a NewsModel and a NewsViewModel. The Newsmodel is declared in the NewsViewModel.

Here is my NewsViewController:

public ActionResult Index(NewsViewModel News)
    {
        //var errors = ModelState.Values.SelectMany(v => v.Errors);

            if (ModelState.IsValid)
            {
                NewsViewRepository NewsRepo = new NewsViewRepository();

                if (NewsRepo.AddNews(News))
                {
                    ViewBag.Message = "News added successfully!";
                    databaseHasChanged = true;
                }
            }


        return View(new NewsViewModel());
    }

This is my NewsViewModel:

public class NewsViewModel
{


    [Required(ErrorMessage = "First name is required.")]
    public NewsModel news { get; set; }

    public bool isvalid { get; set; } 

    private List<SelectListItem> languageItems= new List<SelectListItem>();


    [Required(ErrorMessage = "Language items requierd")]
    public List<SelectListItem> LanguageItems{get;set;}

    [Required(ErrorMessage = "convetion  requierd")]
    private List<SelectListItem> conventionItems = new List<SelectListItem>();

    [Required(ErrorMessage = "convetion  requierd")]
    public List<SelectListItem> ConventionItems {get; set;}


    public int selectedIndex = 1;
}

So the problem i have is that ModelState.IsValid is always false if i don't initalize the NewsModel in the NewsViewModel. If i initialize it it is always true and I dont get to the create view. It ends up in an error. I tried to add a boolean value to the NewsViewModel to set it to true or false and check it with that, but i cant change the value of the boolean in the View. I tried it like this:

@{ Model.isvalid = true }

So is there a way to initalize the Newsmodel in the Razor view so that the modelstate becomes valid? Or do i miss something completly here?

Info: In the previous version of my project i had no viewmodel. Only the newsmodel and there are only strings and integers in it. It worked with them.. the only difference now is that i have this NewsModel in my NewsViewModel class.

I hope somebody can help me. Didn't find any solution to it yet.

  • why do you have model as a part of viewmodel? – Konstantin Ershov Oct 11 '16 at 13:18
  • Possible duplicate of [ModelState.IsValid == false, why?](http://stackoverflow.com/questions/1791570/modelstate-isvalid-false-why) – Sr Julien Oct 11 '16 at 13:29
  • Thats how i understood the explaination of my teacher. He said i could make a viewmodel where i just add the old model to it – David Schmalzer Oct 11 '16 at 13:31
  • Nope its no duplicate i already found this site. but i have a slightly different problem and cant find any solution to it i will add some screenshots in 10 minutes to illustrate it better – David Schmalzer Oct 11 '16 at 13:33
  • http://imgur.com/a/4urqN So i cant set the boolean value to true for some reason.. – David Schmalzer Oct 11 '16 at 13:52
  • View models should never contain data models. Delete it and replace it with the properties of `NewsModel` that you want to display/edit in the view. And your `[Required]` attributes on your `SelectLists` makes no sense and would always cause `ModelState` to be invalid (you do not post back SelectList's –  Oct 11 '16 at 21:41
  • Okey thanks this did the trick, i will mark it as answered. So if I understand correctly if i use a NewsViewModel i dont need the NewsModel anymore. Honestly it don't know why its not allowed to put datamodels into viewmodels but i am ok with that. Thanks again. – David Schmalzer Oct 12 '16 at 17:31

2 Answers2

2

You can lookup into invalid properties of modelstate using

foreach (ModelState modelState in ViewData.ModelState.Values) {
    foreach (ModelError error in modelState.Errors) {
        // errors here 
    }
}
Anupam Singh
  • 1,158
  • 13
  • 25
  • I know what i my error is already. The problem is that NewsViewModel.news = null. thats because the Modelstate.isvalid returns always false. And like i said, if i initalize it in the model directly its always true. But it needs to be false and after i insert the values in the view it needs to be true – David Schmalzer Oct 11 '16 at 13:19
  • well i think you shoud not mark the News field as required then. – Franck Ngako Oct 11 '16 at 13:23
  • Yes because its type of class. – Anupam Singh Oct 11 '16 at 13:24
  • It is requiered because with out it i cant add the news to the database – David Schmalzer Oct 11 '16 at 13:24
  • from what i read, validation works with attribute. so if News is null and required, there is no chance for your viewModel to be valid sadly. – Franck Ngako Oct 11 '16 at 13:31
  • Yes, but it needs to be invalid the first time. So i need to initialize it and add something like a boolean value like i tried it ? – David Schmalzer Oct 11 '16 at 13:38
0

View models should never contain data models. Delete it and replace it with the properties of NewsModel that you want to display/edit in the view. And your [Required] attributes on your SelectLists makes no sense and would always cause ModelState to be invalid (you do not post back SelectList's –