Data not being passed from Razor page - c#

I have a Blazor app that takes user input via a form field and puts it into a database.
However, the data is not being passed from the front end correctly:
Razor file
#using Blogs.Shared.Models
#page "/addpost"
#inject HttpClient Http
#inject NavigationManager NavigationManager
<h2>Create Post</h2>
<hr />
<div class="row">
<div class="col-md-4">
<form>
<div class="form-group">
<label for="Name" class="control-label">Titles</label>
<input for="Name" class="form-control" bind="#posts.title" />
</div>
<div class="form-group">
<label for="Address" class="control-label">Content</label>
<input for="Address" class="form-control" bind="#posts.content" />
</div>
<div class="form-group">
<input type="button" class="btn btn-default" onclick="#(async () => await tas())" value="Save" />
<input type="button" class="btn" onclick="#Cancel" value="Cancel" />
</div>
</form>
</div>
</div>
#functions {
public Posts posts = new();
protected async Task tas()
{
await Http.PostAsJsonAsync("api/Posts/Create", posts);
NavigationManager.NavigateTo("/listposts");
}
void Cancel()
{
NavigationManager.NavigateTo("/listposts");
}
}
What I would expect this to do, is when Save is pressed, the data from Title and Content is assigned to posts and then passed to my POST method:
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Blogs.Shared.Models;
using Microsoft.AspNetCore.Mvc;
namespace Blogs.Server.Controllers
{
public class PostsController : Controller
{
private readonly IDataAccessProvider _dataAccessProvider;
private readonly ILogger _logger;
public PostsController(IDataAccessProvider dataAccessProvider, ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger("PostsController");
_dataAccessProvider = dataAccessProvider;
}
[HttpPost]
[Route("api/Posts/Create")]
public void Create(Posts post)
{
_logger.LogCritical("Data 1", post);
_logger.LogCritical("Data 2", post.content);
_logger.LogCritical("Data 3", post.title);
_dataAccessProvider.AddPosts(post);
}
}
}
All of my _logger.LogCritical lines just return blank, and when the write to the DB occurs it complains that title is empty (this field in my DB is set to NOT NULL).
Can anyone help as to why this is not working?
EDIT
I have updated the code to better match Antoine B's suggestions but its still not working:
#page "/newpost"
#using Blogs.Shared.Models
#inject HttpClient Http
#inject NavigationManager NavigationManager
<h1>#Title Post</h1>
<hr />
<EditForm Model="#posts" OnValidSubmit="SaveUser">
<DataAnnotationsValidator />
<div class="mb-3">
<label for="Name" class="form-label">Title</label>
<div class="col-md-4">
<InputText class="form-control" #bind-Value="posts.title" />
</div>
<ValidationMessage For="#(() => posts.title)" />
</div>
<div class="mb-3">
<label for="Address" class="form-label">Content</label>
<div class="col-md-4">
<InputText class="form-control" #bind-Value="posts.content" />
</div>
<ValidationMessage For="#(() => posts.content)" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Save</button>
<button class="btn btn-light" #onclick="Cancel">Cancel</button>
</div>
</EditForm>
#code {
protected string Title = "Add";
protected Posts posts = new();
protected async Task SaveUser()
{
await Http.PostAsJsonAsync("api/Posts/Create", posts);
Cancel();
}
public void Cancel()
{
NavigationManager.NavigateTo("/listposts");
}
}

To bind a value to an input component you must add an # before the bind property, like following #bind="posts.title" (see https://learn.microsoft.com/en-us/aspnet/core/blazor/components/data-binding?view=aspnetcore-6.0)
That's what's not working for you.
I also don't recommend you to use the #functions because it is not recommended by Microsoft for razor files (see https://learn.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-3.0#functions)
#code {
public Posts posts = new();
protected async Task tas()
{
await Http.PostAsJsonAsync("api/Posts/Create", posts);
NavigationManager.NavigateTo("/listposts");
}
void Cancel()
{
NavigationManager.NavigateTo("/listposts");
}
}
I hope it helped you

Related

Show results on a different page

I have a blazor app that gets some inputs, calculates, and displays some outputs via Edit Form and single model.
Some of the inputs:
<EditForm Model="#model" OnValidSubmit="hundlevalidsubmit">
<div class="form-group">
<label>Full Name</label>
<InputText style="width: 25%" #bind-Value="model.name" class="form-control">
</InputText>
</div>
<div class="form-group">
<label>Type of Vessel</label>
<InputSelect style="width: 25%" #bind-Value="model.typeofvessel" class="form-control">
<option value="">Select the type of Vessel</option>
<option value="5">General Cargo Ship</option>
<option value="10">General Cargo Ship</option>
<option value="15">Roll on-roll off Ship</option>
<option value="20">Bulk Carrier</option>
</InputSelect>
</div>
<div class="form-group">
<label>Gross Tonnage</label>
<InputNumber style="width: 25%" #bind-Value="model.gt" class="form-control" />
</div>
</EditForm>
I then bind the results at the end of the page with
<EditForm Model="#model" OnValidSubmit="hundlevalidsubmit">
<div class="card-body">
<div class="row">
<div class="col">Full Name:</div>
<div class="col text-right">#model.name</div>
</div>
<div class="row">
<div class="col">EEXI Value:</div>
<div class="col text-right">#eexi.ToString("N")</div>
</div>
<div class="row">
<div class="col">Compliance:</div>
<div class="col text-right">#model.compliance</div>
</div>
</div>
</EditForm>
And display them with a calculate button at the end of the page with this:
<EditForm Model="#model" OnValidSubmit="hundlevalidsubmit">
<center>
<div class="checkbox">
<label>
<input name="cbPrivacy" id="cbPrivacy" type="checkbox"> I accept Dromon Bureau of Shipping (Privacy Policy).
</label>
</div>
<div class="col-lg-10 #*col-lg-offset-2*#" style="margin-bottom:20px;">
<button class="btn btn-default btn-medium">Cancel</button>
<button href="/Results" #onclick="#(() => { SendEmail(); })" style="background-color:green;" class="btn btn-primary btn-medium">
Calculate
</button>
#*href="/Results"*#
#* <p>Calculate</p>*#
</div>
</center>
</EditForm>
This is the code that does the calculations
#code {
public infomodel model = new infomodel();
public double eexi;
public void hundlevalidsubmit()
{
eexi = (int.Parse(model.typeofvessel) + model.gt);
if (eexi > 50)
{
model.compliance = "Yes";
}
else
{
model.compliance = "No";
}
}
Now I would like to display the results on a new page (results).
Please note this is my first app so limited technical knowledge.
Method 1:
You can pass parameters to page being navigated like this, if the values are few and not sensitive and are used only in one place
NavigationManager.NavigateTo($“NextPage/{Value1}/{Value2}”);
NextPage:
#page “/nextpage/{value1}/{value2}
[Parameter]
Public string Value1 {get; set;}
[Parameter]
Public string Value2 {get; set;}
Method 2:
It involves using DI to hold global data
Register service like this in program.cs
builder.Services.AddScoped<DataService>();
In first page:
#inject DataService dataService;
dataService.model = new model with calculated values
In second page:
#inject DataService dataService;
Use dataService.model to retrieve values
DataService.cs
Public class DataService{
public infomodel model{get; set;}
}
You can use startup.cs file for DI
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddScoped<DataService>();
}
This one is Blazor server-side .NET 6.0 project
Program.cs
using FinalExiiCalculator.Data;
using FinalExiiCalculator.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();
builder.Services.AddSingleton<DataService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.Run();
**DataService.cs**
using FinalExiiCalculator.Models;
namespace FinalExiiCalculator.Services
{
public class DataService
{
public infomodel infomodel{get; set;} = new();
}
}
**infomodel.cs**
public class infomodel
{
public string compliance { get; set; } = "";
public string typeofvessel { get; set; } = "";
}
counter.razor
#page "/counter"
#using FinalExiiCalculator.Services
#inject DataService dataService
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: #currentCount</p>
<button class="btn btn-primary" #onclick="IncrementCount">Click me</button>
#code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
dataService.infomodel.typeofvessel = "My Vessel";
dataService.infomodel.compliance = "Yes";
}
}
FetchData.razor
#page "/fetchdata"
<PageTitle>Weather forecast</PageTitle>
#using FinalExiiCalculator.Data
#inject WeatherForecastService ForecastService
#using FinalExiiCalculator.Services
#inject DataService dataService
<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from a service.</p>
#if (forecasts == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
#foreach (var forecast in forecasts)
{
<tr>
<td>#forecast.Date.ToShortDateString()</td>
<td>#forecast.TemperatureC</td>
<td>#forecast.TemperatureF</td>
<td>#forecast.Summary</td>
</tr>
}
</tbody>
</table>
<div>
<span>#dataService.infomodel.typeofvessel</span>
<span>#dataService.infomodel.compliance</span>
</div>
}
#code {
private WeatherForecast[]? forecasts;
protected override async Task OnInitializedAsync()
{
forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
}
}

Blazor Role Management Add Role trough UI (Crud)

I'm pretty new to blazor and have gotten myself in some doubt on adding roles to the database.
I have implemented to Identity role management and have a working system.
But now i want to add new roles trough the GUI instead of editing the database.
I have a razor page called RolesOverview.razor
On this page i have a input field and a button.
When i click this button i want to add the text to the roles manager and save it to the database.
This is my razor component
#page "/admin/roles"
#using Microsoft.AspNetCore.Identity
#inject RoleManager<IdentityRole> roleManager
<div class="jumbotron">
<!-- Roles Overview Group Box -->
<div class="row mb-5">
<div class="col-12">
<h1 class="display-6">Roles Options</h1>
<hr class="my-4" />
<div class="row" style="background-color:white; margin-bottom:10px; margin-top:10px;">
<div class="col-12">
<div class="card w-100 mb-3" style="min-width:100%;">
<div class="card-body">
<h5 class="card-title">Roles</h5>
<p class="card-text">
<div class="row">
<div class="col-1">
Role Name:
</div>
<div class="col-10">
<input type="text" style="min-width:100%;" placeholder="Role Type" />
</div>
<div class="col-1">
Add Role
</div>
</div>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Not Getting Saved...
#code {
private string CurrentValue { get; set; }
private async void AddRole()
{
if (CurrentValue != string.Empty)
{
if (!await roleManager.RoleExistsAsync(CurrentValue))
{
await roleManager.CreateAsync(new IdentityRole
{
Name = CurrentValue
});
}
}
}
}
I have no clue on what todo next.
I's it posible todo it with razor component or do i need to do it trough razor page?
Example would be perfect.
Regards Me!
Answer :
<div class="col-10">
<input value="#CurrentValue" #onchange="#((ChangeEventArgs __e) => CurrentValue =__e.Value.ToString())" />
#*<input type="text" style="min-width:100%;" placeholder="Role Type" />*#
</div>
<div class="col-1">
<a #onclick="AddRole" class="btn btn-primary" style="min-width:90px;">Add Role</a>
</div>
#code {
private string CurrentValue { get; set; }
private async void AddRole()
{
if (CurrentValue != string.Empty)
{
if (!await roleManager.RoleExistsAsync(CurrentValue))
{
await roleManager.CreateAsync(new IdentityRole
{
Name = CurrentValue
});
}
}
}
}
You can use RoleManager to create a new role by using the CreateAsync method:
if (!await roleMgr.RoleExistsAsync("RoleName"))
{
await roleManager.CreateAsync(new IdentityRole
{
Name = "RoleName"
});
}

cannot convert from 'method group' to 'bool' in a Razor Page

While trying to Build a public Repo of a Blazor Blog Engine in VS2019 for Mac I encounter the following compile Error and don't know why and how to solve it:
Error CS1503: Argument 3: cannot convert from 'method group' to
'bool' (CS1503)
In the following Razor Page:
#layout MainLayout
#inherits LoginModel
<WdHeader Heading="WordDaze" SubHeading="Please Enter Your Login Details"></WdHeader>
<div class="container">
<div class="row">
<div class="col-md-4 offset-md-4">
<div class="editor">
#if (ShowLoginFailed)
{
<div class="alert alert-danger">
Login attempt failed.
</div>
}
<input type="text" #bind=#LoginDetails.Username placeholder="Username" class="form-control" />
<input type="password" #bind=#LoginDetails.Password placeholder="Password" class="form-control" />
<button class="btn btn-primary" #onclick="#Login">Login</button>
</div>
</div>
</div>
The CS File looks like this:
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using WordDaze.Shared;
namespace WordDaze.Client.Features.Login
{
public class LoginModel : ComponentBase
{
[Inject] private AppState _appState { get; set; }
[Inject] private NavigationManager _navigationManager { get; set; }
protected LoginDetails LoginDetails { get; set; } = new LoginDetails();
protected bool ShowLoginFailed { get; set; }
protected async Task Login()
{
await _appState.Login(LoginDetails);
if (_appState.IsLoggedIn)
{
_navigationManager.NavigateTo("/");
}
else
{
ShowLoginFailed = true;
}
}
}
}
Can you please explain me why this happens and how to solve it?
Solution:
<button class="btn btn-primary" #onclick="#Login">Login</button>
was missing the Parentheses of the Login Method:
<button class="btn btn-primary" #onclick="#Login()">Login</button>
Change the <button> so that the #onclick method doesn't have the #:
<button class="btn btn-primary" #onclick="Login">Login</button>

Model List property is NULL on Post in controller

So I have tested on a clean project an issue I've been getting, and have done the following code setup for checking if a custom Class object still returns null placed in a List:
VIEW
<div>
<div class="jumbotron">
<h1 class="display-4"><span class="fas fa-user-secret"></span> Babcock Canada - Application Template</h1>
<br />
<div class="alert alert-primary" role="alert">
<span class="fas fa-info-circle"></span>
<span> This is the Babcock Canada MVC Application template for use in developing content-rich web applications.</span>
</div>
<hr class="my-4" />
</div>
<div>
<div class="container-fluid">
#if (!string.IsNullOrEmpty(Model.errorMessage))
{
<div class="alert alert-danger" role="alert">
<span class="fas fa-stop-circle"></span> #Html.DisplayFor(alert => alert.errorMessage)
</div>
}
#if (!string.IsNullOrEmpty(Model.successMessage))
{
<div class="alert alert-success" role="alert">
<span class="fas fa-check-circle"></span> #Html.DisplayFor(alert => alert.successMessage)
</div>
}
<div>
#using (Html.BeginForm("TestAction", "Default", FormMethod.Post))
{
#Html.HiddenFor(m => Model.tester[0].tester)
<button type="submit" class="btn btn-primary">
Submit 1
</button>
}
</div>
<div>
#using (Html.BeginForm("TestAction", "Default", FormMethod.Post))
{
#Html.HiddenFor(m => Model.tester[1].tester)
<button type="submit" class="btn btn-primary">
Submit 2
</button>
}
</div>
</div>
</div>
TestClass.cs
namespace Test.Models
{
public class TestClass
{
public string tester { get; set; }
}
}
MODEL
namespace Test.Models
{
/// <summary>
/// This is the default template model.
/// </summary>
public class DefaultModel : SharedModel
{
public string errorMessage = string.Empty;
public string successMessage = string.Empty;
public List<TestClass> tester { get; set; }
public DefaultModel()
{
}
public void Init()
{
tester = new List<TestClass>
{
new TestClass { tester = "Testing..." },
new TestClass { tester = "Testing2..." }
};
}
}
}
CONTROLLER
[HttpPost]
public ActionResult TestAction(DefaultModel model)
{
return View(model);
}
So the result is that the second one returns NULL in the list, but the first one returns just fine.
In my other project index 0 of a list looped in the same way returns the error: "An item with the same key has already been added."
So what am I doing wrong?
try using the helper Html.Hidden() instead
<div>
#using (Html.BeginForm("TestAction", "Default", FormMethod.Post))
{
#Html.Hidden("tester", Model.tester[0].tester)
<button type="submit" class="btn btn-primary">
Submit 1
</button>
}
</div>
<div>
#using (Html.BeginForm("TestAction", "Default", FormMethod.Post))
{
#Html.Hidden("tester", Model.tester[1].tester)
<button type="submit" class="btn btn-primary">
Submit 2
</button>
}
</div>
Turns out it doesn't work when the form is inside the loop, has to be outside and reference an ID value through the submit button holding the name "ID" and the value of that list item.
Suppose using Html.Hidden() would work, but that isn't what was required for the project.

RuntimeBinderException: Cannot perform runtime binding on a null reference

I'm making a create item page, and in this create item page there is a popup modal table where we can choose the type of UoM that we want. And normally when this form is submitted with all of the fields filled in, it saved the values into the database. But when the form is submitted with one or some or all of the fields not filled in, it supposed to give some error message that the fields are required. But it didn't and it shows this error.
These are my code
ItemController
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Threading.Tasks;
using CRMandOMS.Models;
using CRMandOMS.ViewModels;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace CRMandOMS.Controllers
{
public class ItemController : Controller
{
private readonly IItemRepository _itemRepository;
private readonly IUoMRepository _uoMRepository;
public ItemController(IItemRepository itemRepository, IUoMRepository uoMRepository)
{
_itemRepository = itemRepository;
_uoMRepository = uoMRepository;
}
// GET: /<controller>/
public ViewResult Index()
{
var model = _itemRepository.GetAll();
return View(model);
}
public ViewResult Details(Guid? id)
{
Item item = _itemRepository.GetById(id.Value);
return View(item);
}
[HttpGet]
public ViewResult Create()
{
ItemCreateViewModel itemCreateViewModel = new ItemCreateViewModel()
{
UoMs = _uoMRepository.GetAll()
};
return View(itemCreateViewModel);
}
[HttpPost]
public IActionResult Create(ItemCreateViewModel model)
{
if (ModelState.IsValid)
{
Item newItem = new Item
{
Name = model.Name,
Price = model.Price,
UoMId = model.UoMId
};
_itemRepository.Insert(newItem);
return RedirectToAction("Details", new { id = newItem.Id });
}
return View();
}
}
}
Create
#model CRMandOMS.ViewModels.ItemCreateViewModel
#{
ViewData["Title"] = "Item Create";
}
<h2>Item Create</h2>
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a asp-controller="Item" asp-action="Index">Item</a></li>
<li class="breadcrumb-item active" aria-current="page">Create</li>
</ol>
</nav>
<form enctype="multipart/form-data" asp-controller="Item" asp-action="Create" method="post" class="mt-3">
<div class="form-group row">
<label asp-for="Name" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="Name" class="form-control" placeholder="Name" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="Price" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="Price" class="form-control" placeholder="Price" />
<span asp-validation-for="Price" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<label asp-for="UoMId" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<input asp-for="UoMId" id="uomid" class="form-control" hidden />
<div class="input-group mb-3">
<input id="uomname" type="text" class="form-control" placeholder="UoM" aria-label="UoM" aria-describedby="button-uom" disabled>
<div class="input-group-append">
<button class="btn btn-outline-success" type="button" id="button-uom" data-toggle="modal" data-target="#uoMLookupTableModal">Select UoM</button>
</div>
</div>
<span asp-validation-for="UoMId" class="text-danger"></span>
</div>
</div>
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group row">
<div class="col-sm-2"></div>
<div class="col-sm-10">
<a asp-controller="Item" asp-action="Index" class="btn btn-light">Back</a>
<button type="submit" class="btn btn-success">Create</button>
</div>
</div>
</form>
#{
await Html.RenderPartialAsync("_UoMLookup");
}
#section scripts {
<script>
$(document).ready(function () {
var uoMTable = $("#uoMTable").DataTable({
"columnDefs": [
{
"targets": [0],
"visible": false
}
],
"order": [[1, "asc"]]
});
$('#uoMTable tbody').on('click', 'tr', function () {
if ($(this).hasClass('table-success')) {
$(this).removeClass('table-success');
}
else {
uoMTable.$('tr.table-success').removeClass('table-success');
$(this).addClass('table-success');
}
});
$("#getUoM").click(function () {
var uomdata = uoMTable.row('.table-success').data();
//alert(uomdata[0]);
$('#uomid').val(uomdata[0]);
//alert(uomdata[1]);
$('#uomname').val(uomdata[1]);
});
});
</script>
}
_UoMLookup
<div class="modal fade" id="uoMLookupTableModal" tabindex="-1" role="dialog" aria-labelledby="uoMLookupTableModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<table id="uoMTable" class="table table-striped table-bordered table-bordered nowrap" style="width:100%">
<thead>
<tr>
<td>Id</td>
<td>Name</td>
<td>Description</td>
</tr>
</thead>
<tbody>
#foreach (UoM uom in Model.UoMs)
{
<tr>
<td class="uom-id">#uom.Id</td>
<td class="uom-name">#uom.Name</td>
<td>#uom.Description</td>
</tr>
}
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" data-dismiss="modal">Cancel</button>
<button id="getUoM" type="button" class="btn btn-success" data-dismiss="modal">Select</button>
</div>
</div>
</div>
</div>
ItemCreateViewModel
using CRMandOMS.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace CRMandOMS.ViewModels
{
public class ItemCreateViewModel
{
[Required]
[MaxLength(100, ErrorMessage = "Name cannot exceed 100 characters")]
public string Name { get; set; }
[Required(ErrorMessage = "{0} is required")]
[Range(1000, 999999999)]
public int Price { get; set; }
[Required]
public Guid UoMId { get; set; }
public IEnumerable<UoM> UoMs { get; set; }
public string PhotoPath { get; set; }
}
}
In the HTTP POST Create method (ItemController) if the model is not valid (so ModelState.IsValid == false) you are not passing a model to your View. Ensure passing a valid model, as shown in the controller methods tutorial.
But when the form is submitted with one or some or all of the fields not filled in, it supposed to give some error message that the fields are required. But it didn't and it shows this error.
You do not have a reference to validation scripts, make sure you have _ValidationScriptsPartial.cshtml in Shared folder, then modify your code:
#section scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
<script>
//...
</script>
}
For the error on your page, just like other community has said, it is likely that the model state is invalid and it execute return View() without returning any data to create view.
However,your partial view does not allow the Model.UoMs to be null.
In your Create Post action, if the model contains UoMs, you could just use
return View(model)
otherwise ,assign UoMs data to model like what you have done in Create Get action, then return it to view.
You could always use a breakpoint on the Post action to debug the result.

Categories

Resources