2

I am new to ASP.NET Core MVC apps. I am trying to create a web app but I am having an issue about validating my model. I have added model code, controller code and razor page. My model validation fails because razor page doesn't start il model. normally I don't need iller model.

Would you mind anyone can help me about is there any easy solution about validation without custom validation. I am using .NET Core 6.0 and Visual Studio 2022

This is my model class

using System;
using System.Collections.Generic;

namespace OdevProject.Models
{
    public partial class Ilceler
    {
        public Ilceler()
        {
            Adreslers = new HashSet<Adresler>();
            Bolumlers = new HashSet<Bolumler>();
            Doktorlars = new HashSet<Doktorlar>();
            Hastanelers = new HashSet<Hastaneler>();
            Randevulars = new HashSet<Randevular>();
        }

        public int IlceId { get; set; }
        public int IlId { get; set; }
        public string IlceAd { get; set; } = null!;

        public virtual Iller Il { get; set; } = null!;
        public virtual ICollection<Adresler> Adreslers { get; set; }
        public virtual ICollection<Bolumler> Bolumlers { get; set; }
        public virtual ICollection<Doktorlar> Doktorlars { get; set; }
        public virtual ICollection<Hastaneler> Hastanelers { get; set; }
        public virtual ICollection<Randevular> Randevulars { get; set; }
    }
}

and this is controller

public async Task<IActionResult> Create([Bind("IlceId,IlId,IlceAd")] Ilceler ilceler)
{
    //var Il = new Iller { IlId = ilceler.Il.IlId, IlAd=ilceler.Il.IlAd };
    if (ModelState.IsValid)
    {
        var ilce = _context.Ilcelers.Where(x => x.IlceAd == ilceler.IlceAd).FirstOrDefault();

        if (ilce != null)
        {
            ViewBag.Message = "Exist";
            return View();
        }
        else
        {
            _context.Add(ilceler);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
    }

    ViewData["IlId"] = new SelectList(await _context.Illers.ToListAsync(), "IlId", "IlAd");

    //ViewData["Illist"] = new SelectList(await _context.Illers.ToListAsync(), "IlId", "IlAd");
    //ViewData["IlId"] = new SelectList(_context.Illers, "IlId", "IlId", ilceler.IlId);
    return View(ilceler);
} 

and finally razor pages

@model OdevProject.Models.Ilceler 

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

<h1>Create</h1>

<h4>Ilceler</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">                
                <label asp-for="IlId" class="control-label"></label>                
               @* @Html.DropDownList("iller",(IEnumerable<SelectListItem>)ViewData["Illist"],"---Il Seciniz---");*@
                <select asp-for="IlId" class ="form-control" asp-items="ViewBag.IlId"></select>  
            </div>
            <div class="form-group">
                <label asp-for="IlceAd" class="control-label"></label>
                <input asp-for="IlceAd" class="form-control" /> 
                @if (ViewBag.Message != null && ViewBag.Message == "Exist")
        {
            <br /><span style="color:red;">Kayıt mevcut!!!</span>
        }
                <span asp-validation-for="IlceAd" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div> 
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
1

2 Answers 2

3

As this document said:

Beginning with .NET 6, new projects include the <Nullable>enable</Nullable> element in the project file. Once the feature is turned on, existing reference variable declarations become non-nullable reference types.

So that the non-nullable property must be required in asp.net 6, otherwise the ModelState will be invalid.

To achieve your reuiqrement, you can remove <Nullable>enable</Nullable> from your project file.

Or you can initialize the data like below:

public partial class Ilceler
{
    public Ilceler()
    {
        Il = new Iller();   //add here...
        //...
    }
    public int IlceId { get; set; }
    public int IlId { get; set; }
    public string IlceAd { get; set; } = null!;

    public virtual Iller Il { get; set; }
    //...
}
Sign up to request clarification or add additional context in comments.

Comments

0

First of all, thank you for your help. This is how I solved it. Is it the right approach? Or is there a more accurate method?


 public async Task<IActionResult> Create([Bind("IlceId,IlId,IlceAd")] Ilceler ilceler)
        {
            Iller Il = new Iller();
            Il = _context.Illers.Find(ilceler.IlId); 

            if (ModelState.IsValid)
            {
                var ilce = _context.Ilcelers.Where(x => x.IlceAd == ilceler.IlceAd).FirstOrDefault();
                if (ilce != null)
                {
                    ViewBag.Message = "Exist";
                    return View();
                }
                else
                {
                    _context.Add(ilceler);
                    await _context.SaveChangesAsync();
                    return RedirectToAction(nameof(Index));
                }
            }
            ViewData["IlId"] = new SelectList(await _context.Illers.ToListAsync(), "IlId", "IlAd"); 

1 Comment

Actually it didn't for me so tried this approach

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.