Home > Net >  A server side validation problem at razor page
A server side validation problem at razor page

Time:12-06

Below is a small part of my data insert form. My problem is; The first form object is for the name of the Class room. The field is required and I wanna validate it at server side . In normal it works for sure. But since the next form object is an dropdown menu which get filled from a table of my database, the validation doesn't work. When i post it with empty class room field I get a error. Normaly it is expected that the server side validation work and stop the posting action right ? But it doesn't. What do I miss here ? Thank you.

PS: The teacher field in DB is nullable and when i type something in the class room textbox the form works w/o any problem.

...
...
<div >
    <input type="text" asp-for="AddClassRoom.Class"  />
    <label asp-for="AddClassRoom.Class"></label>
    <span asp-validation-for="AddClassRoom.Class" ></span>
</div>
<div >
    <select  asp-for="AddClassRoom.Teacher" asp-items="@(new SelectList(Model.ApplicationUser.OrderBy(x => x.NameSurname).ToList(),"Id","NameSurname"))">
    <option value="">select...</option>
    </select>
    <label asp-for="AddClassRoom.Teacher"></label>
<span asp-validation-for="AddClassRoom.Teacher" ></span>
</div>
...
...

CodePudding user response:

With reference to you comment:

Error is; null parameter(source). Well this is ok, i know it. But there must be a simple way to validate an insert form who has an Database driven content dropdown menu. Post and don't get null after server side validation.

It seems that the dropdown values are not populated after posting the form. Since you have the dropdown values are coming from DB, you need to get its items again from DB after posting the form, so the razor page can fill it again.

More support can be provided if you share your backend code.

[Sample]

Here is a basic sample depending on your code;

<select  asp-for="AddClassRoom.Teacher" asp-items="@(new SelectList(Model.ApplicationUser.OrderBy(x => x.NameSurname).ToList(),"Id","NameSurname"))">
    <option value="">select...</option>
    </select>

Backend:


public ActionResult OnGet() {
    // ...

    ApplicationUsers = GetApplicationUsersFromDb();

    Return Page();
}

public ActionResult OnPost() {
    // ...

    ApplicationUsers = GetApplicationUsersFromDb();

    Return Page();
}
  • Related