0

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?

4
  • Hi @Gökhan Aldanmaz,where is your view,it's under your Area? Commented Jan 15, 2021 at 7:06
  • Show the controller method Commented Jan 15, 2021 at 7:21
  • Does your view reference TagHelper? @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers Commented Jan 15, 2021 at 7:40
  • No problem about taghelpers, i did not show them in my question, thank you @Yinqiu Commented Jan 15, 2021 at 7:44

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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();  
        }  
    }  
} 

1 Comment

Yes , i am controlling like this way, but error messages are not showing. ViewModel block this validations? I must make validation in view model without model?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.