简体   繁体   中英

MVC model validation and printing errors

I have the following controller action which validates me a list of models

public ActionResult Translate(int RoleId, ICollection<RTFM> list)
        {
            bool IsValid = true;
            foreach (var item in list)
            {
                ModelState.Clear();
                TryValidateModel(item);
                if (!ModelState.IsValid)
                {
                    IsValid = false;
                }
            }
            if (IsValid)
            {
                foreach (var item in list)
                {
                    ...
                    db.SaveChanges();
                }
                return RedirectToAction("Translate", new { Id = RoleId });
            }
            ViewBag.RoleId = RoleId;
            return View(list);
        }

That function validates each model from my list correctly but adds the errors to model state. How can I show this errors for each field from my list if the validation goes wrong? Should I do the validation in another way?

This way I can print each error from ModelState for each field but they will not be shown near each field.

This is how a field of my view looks like:

@Html.ValidationSummary(true)

...
<div class="form-group">
                        @Html.LabelFor(model => model[i].Name, new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.TextAreaFor(model => model[i].Name)
                            @Html.ValidationMessageFor(model => model[i].Name)
                        </div>
                    </div>

It seems that if I make the validation this way, it works. I didn't knew you can make validation for an entire collection.

if (ModelState.IsValid)
            {
                foreach (var item in list)
                {
                    ...
                    db.SaveChanges();
                }
            }

Is any other better way?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM