Decimal not recognized ASP.NET - c#

I'm trying to insert a decimal number in one form but with no success. Everytime, I get this:
My entity is declared like this:
public class Serie
{
public int Id { get; set; }
public string Name { get; set; }
[RegularExpression(#"^\d+\.\d{0,2}$")]
[Range(0, 9999999999999999.99)]
public decimal Price { get; set; }
public string Description { get; set; }
public List<Season> Seasons { get; set; }
public List<Rental> Rentals { get; set; }
public List<Assessment> Assessments { get; set; }
}
On my razor page I have this on html side:
#page
#model Shows4All.Pages.Series.CreateModel
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Serie</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Serie.Name" class="control-label"></label>
<input asp-for="Serie.Name" class="form-control" />
<span asp-validation-for="Serie.Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Serie.Price" class="control-label"></label>
<input type="number" asp-for="Serie.Price" class="form-control" />
<span asp-validation-for="Serie.Price" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Serie.Description" class="control-label"></label>
<input asp-for="Serie.Description" class="form-control" />
<span asp-validation-for="Serie.Description" 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-page="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
I already tried without Data annotation and withou type="number" on html side...but it doesn't work. Any idea how can it be solved?

Try to add locale configuration in your aspet.config file like this:
<configuration>
<system.web>
<globalization culture ="en-US" />
</system.web>
</configuration>
If didn't work, try remove the Regex attribute and test it again.

Related

Bind Image src to IFormFile asp.net core

I am starting to learn Asp.Net core. I have a model class which is saved to the database as follows,
public class BlogData
{
public int Id { get; set; }
public string BlogTitle { get; set; }
public string BlogContent { get; set; }
public DateTime PostedDateTime { get; set; }
public byte[] ImageData { get; set; }
}
Now I created an other class as follows,
public class BlogDataWithStringImage : BlogData
{
private IFormFile _actualImage;
public IFormFile ActualImage
{
get => _actualImage;
set
{
if (value != null)
{
using var fs1 = value.OpenReadStream();
using var ms1 = new MemoryStream();
fs1.CopyTo(ms1);
ImageData = ms1.ToArray();
}
_actualImage = value;
}
}
}
Problem: My intention is when some value gets bound to the ActualImage property, I want to convert it to byte Array. Problem is, when I keep a breakpoint on the set block of (ActualImage property in BlogDataWithStringImage class) the breakpoint never gets hit even when I choose the image on the View. Please help.
#model KGSBlog.Models.BlogDataWithStringImage
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>BlogData</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="BlogTitle" class="control-label"></label>
<input asp-for="BlogTitle" class="form-control" />
<span asp-validation-for="BlogTitle" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="BlogContent" class="control-label"></label>
<input asp-for="BlogContent" class="form-control" />
<span asp-validation-for="BlogContent" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PostedDateTime" class="control-label"></label>
<input asp-for="PostedDateTime" class="form-control" />
<span asp-validation-for="PostedDateTime" class="text-danger"></span>
</div>
<div class="col-md-12">
<div class="form-group">
<label asp-for="ActualImage" class="control-label"></label>
<div class="custom-file">
<input asp-for="ActualImage" class="custom-file-input" id="customFile">
<label class="custom-file-label" for="customFile">Choose file</label>#*Choosing an image never sets the ActualImage property*#
</div>
<span asp-validation-for="ActualImage" class="text-danger"></span>
</div>
</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");}
}
Ok I figured it out. I was refering to this post in case if it helps someone, Image upload asp.net core
I added the following script inside the Scripts section as in the above post and it works fine.
<script type="text/javascript">
$(".custom-file-input").on("change", function () {
var fileName = $(this).val().split("\\").pop();
$(this).siblings(".custom-file-label").addClass("selected").html(fileName);
});
</script>

Populate DropDown List in MVC App that Consumes a Web API

I have a simple MVC app that is consuming a web api via REST. The controller in the MVC app makes http calls to the web api to populate views within the MVC app with razor syntax.
I am trying to figure out how to populate a drop down list on one of the 'create' actions. I'm currently just using the scaffolded page:
#model ComicBookInventory.Shared.ComicBookWithAuthorsAndCharactersViewModel
#{
ViewData["Title"] = "CreateComicBook";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>CreateComicBook</h1>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="CreateComicBook">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Id" class="control-label"></label>
<input asp-for="Id" class="form-control" />
<span asp-validation-for="Id" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Title" class="control-label"></label>
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Description" class="control-label"></label>
<input asp-for="Description" class="form-control" />
<span asp-validation-for="Description" class="text-danger"></span>
</div>
<div class="form-group form-check">
<label class="form-check-label">
<input class="form-check-input" asp-for="IsRead" /> #Html.DisplayNameFor(model => model.IsRead)
</label>
</div>
<div class="form-group">
<label asp-for="DateRead" class="control-label"></label>
<input asp-for="DateRead" class="form-control" />
<span asp-validation-for="DateRead" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Rating" class="control-label"></label>
<input asp-for="Rating" class="form-control" />
<span asp-validation-for="Rating" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Genre" class="control-label"></label>
<input asp-for="Genre" class="form-control" />
<span asp-validation-for="Genre" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="CoverUrl" class="control-label"></label>
<input asp-for="CoverUrl" class="form-control" />
<span asp-validation-for="CoverUrl" 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");
}
}
Which gets populated from this action in the controller:
public async Task<IActionResult> CreateComicBook(ComicBookWithAuthorsAndCharactersViewModel model)
{
string uri = $"https://localhost:5001/api/comicbook/add-book/";
HttpClient client = _httpClientFactory.CreateClient(
name: "ComicBookInventory.Api");
var postTask = await client.PostAsJsonAsync<ComicBookWithAuthorsAndCharactersViewModel>(uri, model);
if (postTask.IsSuccessStatusCode)
{
return RedirectToAction("GetAllComics");
}
else
{
return View(model);
}
}
Here is the view model definition:
namespace ComicBookInventory.Shared
{
public class ComicBookWithAuthorsAndCharactersViewModel
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public bool IsRead { get; set; }
public DateTime? DateRead { get; set; }
public int? Rating { get; set; }
public string Genre { get; set; }
public string? CoverUrl { get; set; }
/// <summary>
/// Navigation properties
/// </summary>
/// a book can have many authors
public ICollection<string>? AuthorNames { get; set; }
public ICollection<string>? CharacterNames { get; set; }
}
}
My question is, I want to add a drop down checklist to the view, so that when I am creating a comic book, I can select Authors that currently exist in the database. The same for characters.
Here is the entire code base in case anyone is interested: https://github.com/rnemeth90/ComicBookInventoryApp
I normally try and figure things out on my own (I'm relatively new to EF Core, and have very little experience with many-to-many relationships in EF core). I have tried various things and struggled with this for most of my weekend. I feel like this should be relatively simple but cannot figure it out. Please help.
In your Code, I noticed that you used #Html.DropDownList to realzie the selector element, and using form submit to handle the data. So I did a test in my side:
#{
List<SelectListItem> listItems= new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = "Exemplo1",
Value = "Exemplo1_v"
});
listItems.Add(new SelectListItem
{
Text = "Exemplo2",
Value = "Exemplo2_v",
Selected = true
});
listItems.Add(new SelectListItem
{
Text = "Exemplo3",
Value = "Exemplo3_v"
});
}
<form asp-action="Create">
<div class="form-group">
AuthorNames
<div class="col-md-10">
#Html.DropDownListFor(model => model.Author, listItems, "-- Select author --")
</div>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
My model contains a public string? Author { get; set; } property, and when I click the submit button, the select value will be submitted, so when you want to pass the FullName to your controller, you need to set it as the Value of the SelectListItem.

How to fix http error 400 with microsoft ASP.NET MVC create command

I'm setting up a first C# ASP.NET MVC application using Microsofts tutorial. https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-model?view=aspnetcore-2.2&tabs=visual-studio
In the process of this tutorial, it asks to check if the create movies works, but when I attempt to use it, I get an HTTP error 400 - bad request. I believe the data I am entering is accurate, but I can't seem to get anything but a bad request, does anyone know how to fix this.
Model class:
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace MvcMovie.Models
{
public class Movie
{
public int Id { get; set; }
public string Title { get; set; }
[Display(Name = "Release Date")]
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
[Column(TypeName = "decimal(18, 2)")]
public decimal Price { get; set; }
}
}
Razor view:
#model MvcMovie.Models.Movie
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Movie</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="Title" class="control-label"></label>
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ReleaseDate" class="control-label"></label>
<input asp-for="ReleaseDate" class="form-control" />
<span asp-validation-for="ReleaseDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Genre" class="control-label"></label>
<input asp-for="Genre" class="form-control" />
<span asp-validation-for="Genre" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Price" class="control-label"></label>
<input asp-for="Price" class="form-control" />
<span asp-validation-for="Price" 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");}
}
Controller action method:
public async Task<IActionResult> Create([Bind("Id,Title,ReleaseDate,Genre,Price")] Movie movie)
{
if (ModelState.IsValid)
{
_context.Add(movie);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(movie);
}
The expected output is to add to the database, but but the actual output is bad request.
Do you have httpPost over method of controller and why you not use model?
[HttpPost]
public async Task<IActionResult> Create([Bind("Id,Title,ReleaseDate,Genre,Price")] ....
I was using google chrome, and firefox. Apparently it won't let me test on anything except edge or IE

How to Edit Enumerable or List View in MVC Net Core

How do I create a Edit View for a List?
The following is a sample view and model for a single item, which works correctly.
Next question is, I have a list of items I want to edit. How would I conduct this?
Model:
public partial class ProductViewModel
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public string ImageLocation { get; set; }
}
Successful View:
#model ProductViewModel
#{
ViewData["Title"] = "Edit";
}
<h2>Edit</h2>
<h4>Product</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="ProductId" />
<div class="form-group">
<label asp-for="ProductName" class="control-label"></label>
<input asp-for="ProductName" class="form-control" />
<span asp-validation-for="ProductName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ProductDescription" class="control-label"></label>
<input asp-for="ProductDescription" class="form-control" />
<span asp-validation-for="ProductDescription" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</form>
</div>
</div>
Now, I have a model with a list of items, how do I access them in the view? I want to edit all the items in my shopping cart, more specifically the quantity. Trying to call the delegate linq queries correctly.
Error:
The name 'modelItem' does not exist in the current context.
Model:
using System.Collections.Generic;
public class ShoppingCart : List<CartLine>
{
public ShoppingCart() { }
public ShoppingCart(IEnumerable<CartLine> collection) : base(collection) { }
public ShoppingCart(int capacity) : base(capacity) { }
}
public class ShoppingCartViewModel
{
public ShoppingCart ShoppingCart { get; set; }
public string ReturnUrl { get; set; }
}
public class CartLine
{
public int CartLineId { get; set; }
public Product Product { get; set; }
public int Quantity { get; set; }
}
View is not working, error below at input type and further:
#model ShoppingCartViewModel
#{
ViewData["Title"] = "Index";
}
<h2>Edit Shopping Cart</h2>
<h4>edit</h4>
<hr />
<div class="row">
<div class="col-md-4">
#foreach (var item in Model.ShoppingCart)
{
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="modelItem=>item.CartLineId" />
<div class="form-group">
<label asp-for="modelItem=>item.Product.ProductName" class="control-label"></label>
<input asp-for="modelItem=>item.Product.ProductName" class="form-control" />
<span asp-validation-for="modelItem=>item.Product.ProductName" class="text-danger"></span>
</div>
You don't need to use a model expression in asp tag helpers. You can use the # symbol to access the item directly within the foreach loop.
So instead of asp-for="modelItem=>item.Product.ProductName" it would become asp-for="#item.Product.ProductName".
#foreach (var item in Model.ShoppingCart)
{
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="#item.CartLineId" />
<div class="form-group">
<label asp-for="#item.Product.ProductName" class="control-label"></label>
<input asp-for="#item.Product.ProductName" class="form-control" />
<span asp-validation-for="#item.Product.ProductName" class="text-danger"></span>
</div>
</form>
}
Have a look at the docs for more info.

asp.net scaffolded generate item - select tag without options from database

I try to reinterpretate [this simple tutorial][1]
In Book model I remove ScaffoldColumn(false) above public int AuthorID to have select AuthorID in my view.
After rebiuld I can see this select in Books/Create but it has no options.
In my database I can see, that all my items added in SampleData model has BookID and AuthorID.
Why it has no result in html ?
Edited:
My Book.cs
using System.ComponentModel.DataAnnotations;
namespace ContosoBooks.Models
{
public class Book
{
public int BookID { get; set; }
[Required]
public string Title { get; set; }
public int Year { get; set; }
[Range(1, 500)]
public decimal Price { get; set; }
public string Genre { get; set; }
public int AuthorID { get; set; }
// Navigation property
public virtual Author Author { get; set; }
}
}
My Author.cs
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace ContosoBooks.Models
{
public class Author
{
public int AuthorID { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "First Name")]
public string FirstMidName { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
}
My Scaffolded generated View for Books Create (Create.cshtml)
#model ContosoBooks.Models.Book
#{
ViewData["Title"] = "Create";
}
<h2>Create</h2>
<form asp-action="Create">
<div class="form-horizontal">
<h4>Book</h4>
<hr />
<div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="AuthorID" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="AuthorID" class ="form-control"></select>
</div>
</div>
<div class="form-group">
<label asp-for="Genre" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Genre" class="form-control" />
<span asp-validation-for="Genre" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="Price" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Price" class="form-control" />
<span asp-validation-for="Price" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="Title" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="Year" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Year" class="form-control" />
<span asp-validation-for="Year" class="text-danger" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
</form>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
}
[1]: http://docs.asp.net/en/latest/tutorials/your-first-aspnet-application.html
On your create page it won't display the ID because it has no value and the application is anticipating the ID will be generated when the object is inserted into the database.

Categories

Resources