0

I want to have News can have multiple NewsCategories. one-to-many relationship. I am trying to pass categories to MVC controller (post create action). But ModelState.IsValid is always failed. I think my post action does not get selected values from view somehow..

Please help my friend geeks!

I have News.cs:

public class News
{
    public long NewsId { get; set; }
    public ICollection<NewsCategory> NewsCategories { get; set; }
}

I have NewsCategory.cs:

public class NewsCategory
{
    public int NewsCategoryId { get; set; }
    public long NewsId { get; set; }
    public string Title { get; set; }
}

I have NewsController.cs:

// GET: News/Create
    public IActionResult Create()
    {
        List<NewsCategory> newsCategories = new List<NewsCategory>();
        newsCategories = (from s in _context.NewsCategory select s).OrderBy(m => m.Title).ToList();
        newsCategories.Insert(0, new NewsCategory { NewsCategoryId = 0, Title = "Select" });
        ViewBag.NewsCategories = newsCategories;
        return View();
    }

And this is Create Post action:

// POST: News/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Title,Content,NewsTagName1,NewsTagName2")]News news,  List<IFormFile> files)
    {
        if (ModelState.IsValid)
        {
            _context.Add(news);

            var newsCategories = news.NewsCategories;
            foreach(var item in newsCategories)
            {
                item.NewsId = news.NewsId;
                _context.NewsCategory.Add(item);
            }
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(news);
    }

But always fails on 'Model.IsValid' Here is snapshot of what's in object News. enter image description here

Here is the error message: enter image description here

Here is News create view:

@model Carsubfax.Models.News

@{
    ViewData["Title"] = "Create";
}


        <form asp-action="Create" id="comment-form" name="comment-form" method="post" enctype="multipart/form-data">
            <div class="row">
                <div class="col-md-10 col-md-offset-1">
                    <div class="form-group">
                        <label asp-for="Title" class="control-label"></label>
                        <input asp-for="Title" class="form-control" id="txtTitle" autocomplete="off" required="required" placeholder="Enter your news title." />
                        <span asp-validation-for="Title" class="text-danger"></span>
                    </div>
                </div>
                <div class="col-md-10 col-md-offset-1">
                    <div class="form-group">
                        <label class="control-label">News Cover Image<span style="color:red">*</span></label>
                        <input type="file" name="files" required />
                    </div>
                </div>
                <div class="col-md-10 col-md-offset-1">
                    <div class="form-group">
                        <label class="control-label">News Category</label>
                        <select asp-for="NewsCategories" class="form-control" asp-items="@(new SelectList(ViewBag.NewsCategories, "NewsCategoryId", "Title"))" required="required"></select>
                    </div>
                <div class="col-md-10 col-md-offset-1">
                    <div class="form-group text-center">
                        <button type="submit" class="btn btn-primary" onclick="return btnSubmit_clik();">POST</button>
                    </div>
                </div>
                <div class="col-md-10 col-md-offset-1">
                    <div class="form-group text-center">
                        <a asp-action="Index">Back to List</a>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>
Seong E Kim
  • 55
  • 1
  • 2
  • 6
  • If you are not sure try this approach to find out which property is failing [How to figure out which key of ModelState has error](https://stackoverflow.com/questions/15296069/how-to-figure-out-which-key-of-modelstate-has-error) – Shyju Sep 08 '18 at 16:49
  • I added picture where it fails. – Seong E Kim Sep 08 '18 at 16:56
  • You need to repopulate `ViewBag.NewsCategories` before returning the view (when model validation fails) – Shyju Sep 08 '18 at 16:57
  • Could you show Javascript code? I want to see btnSubmit_clik() event, my friend. – Tomato32 Sep 08 '18 at 18:24
  • form is asp form so I don't use JS – Seong E Kim Sep 08 '18 at 18:27
  • I fail to reproduce your issue with these demo code? Share us the `ModelState`. I assume it is related with other properties in `News`, share us the complete code which could repoduce your issue. What is `Title,Content,NewsTagName1,NewsTagName2` for `News`? – Edward Sep 10 '18 at 07:12
  • I make it work passing ModelState.IsValid. However, news.NewsCategories is always null (count = 0) in httpPost Create action. – Seong E Kim Sep 10 '18 at 18:07

0 Answers0