简体   繁体   中英

ASP.NET Core MVC model validation in viewmodel with base model

I am developing a web app with ASP.NET Core MVC, and I have a problem with model validation.

When I set validation in class and then use it in view model, validation does not work. How can I struggle with it?

This is my code:

public class Il : IEntity
{
    [Required(ErrorMessage = "Kodu boş geçilemez")]
    public int IlKodu { get; set; }
    public int UlkeId { get; set; }
    [Required(ErrorMessage = "Ad boş geçilemez")]
    public string Ad { get; set; }
    public int Id { get; set; }
    public DateTime? KayitTarihi { get; set; }
    public DateTime? GuncellemeTarihi { get; set; }
}

ViewModel class;

public class IlAddViewModel
{
    public Il Il { get; set; }
    public List<Ulke> Ulkeler{ get; set; }
}

Then the view:

<div class="container pt-4 eklemeDiv col-4">
<form  asp-controller="Il" asp-action="Add" asp-area="Admin" method="post">
    <div class="form-group">
        <label asp-for="Il.IlKodu">Il Kodu</label>
        <input asp-for="Il.IlKodu" class="form-control" placeholder="İl Kodu Giriniz">
        <span asp-validation-for="Il.IlKodu" class="text-danger"></span>
    </div>

    <div class="form-group">
        <label asp-for="Il.Ad">Il Kodu</label>
        <input asp-for="Il.Ad" class="form-control" placeholder="İl Kodu Giriniz">
        <span asp-validation-for="Il.Ad" class="text-danger"></span>
    </div>

    <div class="form-group">
        <label >Ülke</label>
        <select style="width: 100%;height:30px" id="selectIl" asp-for="Il.UlkeId"
                asp-items="@(new SelectList(Model.Ulkeler,"Id","Ad"))">
            <option>Lütfen Seçim Yapınız</option>
        </select>
    </div>


    <input id="btnIlEkle" type="submit" value="Ekle" class="btn btn-xs btn-success" />
    <a class="btn btn-xs btn-primary" asp-action="Anasayfa" asp-area="Admin" asp-controller="Admin"><i class="fas fa-chevron-left"></i>Anasayfaya Dön</a>
</form>
</div>

The view model does not show validation messages in view. And also how can I show validation messages for list elements?

My friends, all parts of my code are correct for structure, just one error is missing and finally i found it today. I am sharing this solution to help others;

Also controller code;

[HttpPost]
    public async Task<ActionResult> Add(IlAddViewModel ilAddViewModel)
    {
        
        var kayitVarmi = _ilService.BenzerKayitVarMi(ilAddViewModel.Il.IlKodu, ilAddViewModel.Il.Ad);
        if (kayitVarmi)
        {
            TempData.Add("Hata", "Böyle bir kayıt mevcut");
            return RedirectToAction("Add");
        }
        else
        {
            if (ModelState.IsValid && !kayitVarmi)
            {
                ilAddViewModel.Il.KayitTarihi = DateTime.Now;
                await _ilService.Add(ilAddViewModel.Il);                   
                TempData.Add("Message", String.Format("{0} başarıyla eklendi", ilAddViewModel.Il.Ad));
                return RedirectToAction("Anasayfa", "Admin", new { Area = "Admin" });

            }
        }
        return RedirectToAction("Add");
    }

To achieve this validation error, you must add necessary javascript packages as below;

<script src="~.../jquery-validation/dist/jquery.validate.js"></script>
<script src="~.../jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.js"></script>

These javascript packages help to show validation messages without making post to action method.

In the controller you will have access to check the model state to verify if it is valid or not. The controller code should like this

public class HomeController : Controller  
{  
    // GET: Home  
    public ActionResult Index()  
    {  
        return View();  
    }  

    [HttpGet]  
    public ActionResult Create()  
    {  
        return View();  
    }  

    [HttpPost]  
    public ActionResult Create(Employee employee)  
    {  
        try  
        {  
//Here ModelState.IsValid will be true in case all the required fields that are mentioned in employee class
            if (ModelState.IsValid)  
            {  
               return RedirectToAction("Index");  
            }  

            return View();  
        }  
        catch (Exception)  
        {  
            return View();  
        }  
    }  
} 

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