简体   繁体   中英

Input string was not in a correct format. asp.net

I get a Input string was not in a correct format. error when I want to post the form. It does not even reach the target action

But I did not have this problem before

Error:

FormatException: Input string was not in a correct format.
System.Text.ValueStringBuilder.ThrowFormatError()
System.Text.ValueStringBuilder.AppendFormatHelper(IFormatProvider provider, string format, ParamsArray args)
string.FormatHelper(IFormatProvider provider, string format, ParamsArray args)
string.Format(IFormatProvider provider, string format, object arg0)
System.ComponentModel.DataAnnotations.ValidationAttribute.FormatErrorMessage(string name)
System.ComponentModel.DataAnnotations.ValidationAttribute.IsValid(object value, ValidationContext validationContext)
System.ComponentModel.DataAnnotations.ValidationAttribute.GetValidationResult(object value, ValidationContext validationContext)
Microsoft.AspNetCore.Mvc.DataAnnotations.DataAnnotationsModelValidator.Validate(ModelValidationContext validationContext)
Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.ValidateNode()
Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.VisitSimpleType()
Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.VisitImplementation(ref ModelMetadata metadata, ref string key, object model)
Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.Visit(ModelMetadata metadata, string key, object model)
Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.VisitChildren(IValidationStrategy strategy)
Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.VisitComplexType(IValidationStrategy defaultStrategy)
Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.VisitImplementation(ref ModelMetadata metadata, ref string key, object model)
Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.Visit(ModelMetadata metadata, string key, object model)
Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.Validate(ModelMetadata metadata, string key, object model, bool alwaysValidateAtTopLevel, object container)
Microsoft.AspNetCore.Mvc.ModelBinding.ObjectModelValidator.Validate(ActionContext actionContext, ValidationStateDictionary validationState, string prefix, object model, ModelMetadata metadata, object container)
Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.EnforceBindRequiredAndValidate(ObjectModelValidator baseObjectValidator, ActionContext actionContext, ParameterDescriptor parameter, ModelMetadata metadata, ModelBindingContext modelBindingContext, ModelBindingResult modelBindingResult, object container)
Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.BindModelAsync(ActionContext actionContext, IModelBinder modelBinder, IValueProvider valueProvider, ParameterDescriptor parameter, ModelMetadata metadata, object value, object container)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
System.Runtime.CompilerServices.ValueTaskAwaiter<TResult>.GetResult()
Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider+<>c__DisplayClass0_0+<<CreateBinderDelegate>g__Bind|0>d.MoveNext()
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Form:

@model Project.Models.Product

@{
    ViewData["Title"] = "Create";
    Layout = "~/Views/Shared/_AdminLayout.cshtml";
}

<h1>Add Product</h1>

<hr />
<div class="row">
    <form id="CreateForm" asp-action="Create" enctype="multipart/form-data">
        <div class="col-md-8">

            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Price" class="control-label"></label>
                <input type="number" name="Price" class="form-control" />
                <span asp-validation-for="Price" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input type="text" name="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ShortDescription" class="control-label"></label>
                <textarea name="ShortDescription" class="form-control" id="ShortDescription"></textarea>
                <span asp-validation-for="ShortDescription" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Description" class="control-label"></label>
                <textarea name="Description" class="form-control" id="Description"></textarea>
                <span asp-validation-for="Description" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>

        </div>
        <div class="col-md-4">
            <div class="panel panel-primary">
                <div class="panel-heading">picture</div>
                <div class="panel-body">
                    <img id="productimage" class="thumbnail" src="/images/Products/Original/nophoto.jpg" />
                    <div class="form-group">
                        <input type="file" name="img" id="uploadimage" onchange="loadFile(event)" />
                        <span asp-validation-for="ImageName" class="text-danger"></span>
                    </div>
                </div>
            </div>

            <div class="file-upload-wrapper"> 
                <input name="file" id="File" onchange='getFileName()' type="file" class="file-upload-field" value="">
            </div>          
            <label id="FileName"></label>

        </div>



    </form>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script src="https://cdn.ckeditor.com/4.16.2/standard/ckeditor.js"></script>
    <script>

        function readURL(input) {

            if (input.files && input.files[0]) {
                var reader = new FileReader();

                reader.onload = function (e) {
                    $('#productimage').attr('src', e.target.result);
                }

                reader.readAsDataURL(input.files[0]);
            }
        }

        $("#uploadimage").change(function () {
            readURL(this);
        });
        CKEDITOR.replace('Description');
        CKEDITOR.replace('ShortDescription');
        function getFileName() {
            let file = document.getElementById('File');

            let lbl = document.getElementById('FileName');
            lbl.innerHTML = file.value.replace(/.*(\/|\\)/, '');
        }
    </script>
}

Model:

    public class Product
    {
        [Key]
        public int ProductId { get; set; }
        [Display(Name ="قیمت")]
        [Required(ErrorMessage ="لطفا {۰} را وارد کنید")]

        public uint Price { get; set; }
        [Display(Name = "نام محصول")]
        [Required(ErrorMessage = "لطفا {۰} را وارد کنید")]   
        [MaxLength(50)]
        public string Name { get; set; }
        [Display(Name = "توضیح کوتاه")]
        [Required(ErrorMessage = "لطفا {۰} را وارد کنید")]
        [MaxLength(1500)]
        public string ShortDescription { get; set; }
        [Display(Name = "توضیح کامل")]
        [Required(ErrorMessage = "لطفا {۰} را وارد کنید")]
        public string Description { get; set; }
        [MaxLength(42)]
        public string ImageName { get; set; }   
        [Display(Name = "فایل")]
        [Required(ErrorMessage = "لطفا {۰} را وارد کنید")]
        [MaxLength(42)]
        public string File { get; set; } 
        public DateTime Date { get; set; }
    }

action:

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("ProductId,Price,Name,ShortDescription,Description,ImageName,File")] Product product, IFormFile img,IFormFile file)
        {
            if (ModelState.IsValid)
            {
                if (file==null)
                {
                    ViewBag.Error = "لطفا فایل را اضافه کنید";
                    return View(product);

                }
                product.Date = DateTime.Now;
                product.ImageName = "nophoto.jpg";
                if (img != null && img.IsImage())
                {
                    product.ImageName = Guid.NewGuid().ToString() + Path.GetExtension(img.FileName);
                    string savePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images/Products/Original", product.ImageName);

                    using (var stream = new FileStream(savePath, FileMode.Create))
                    {
                        img.CopyTo(stream);
                    }

                    ImageConvertor imgResizer = new ImageConvertor();
                    string thumbPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images/Products/Thumb", product.ImageName);

                    imgResizer.Image_resize(savePath, thumbPath, 150);
                }
                _context.Add(product);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(product);
        }

ValidationAttribute.FormatErrorMessage() is throwing Input string was not in a correct format error.

This is because of your Errormessages in your Model. For example [Required(ErrorMessage = "لطفا {۰} را وارد کنید")]

The error is because of {} . It has special meaning in C#. So you have to use escape character for that.

Example: (ErrorMessage = "Your characters should be in: ,#$%&()*+.-:/;?<=>?@[]^_{{|}}~"

So for escaping { , you have to use double { .

I'm guessing this is due to the CLDR defining the error messages in your entities. try to change Persian terms to English ones.

[Required(ErrorMessage ="لطفا {۰} را وارد کنید")]

to

[Required(ErrorMessage ="Please enter x")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM