• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Mvc.ModelState类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Web.Mvc.ModelState的典型用法代码示例。如果您正苦于以下问题:C# ModelState类的具体用法?C# ModelState怎么用?C# ModelState使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



ModelState类属于System.Web.Mvc命名空间,在下文中一共展示了ModelState类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: BindModel

        public object BindModel(ControllerContext controllerContext,
                                ModelBindingContext bindingContext)
        {
            ValueProviderResult valueResult = bindingContext.ValueProvider
                .GetValue(bindingContext.ModelName);

            ModelState modelState = new ModelState {Value = valueResult};

            object actualValue = null;
            try
            {
                if (!string.IsNullOrEmpty(valueResult.AttemptedValue))
                {
                    actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
                                                CultureInfo.CurrentCulture);
                }
            }
            catch (FormatException e)
            {
                modelState.Errors.Add(e);
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return actualValue;
        }
开发者ID:pragmasolutions,项目名称:avicola,代码行数:25,代码来源:DecimalModelBinder.cs


示例2: ErrorsProperty

        public void ErrorsProperty() {
            // Arrange
            ModelState modelState = new ModelState();

            // Act & Assert
            Assert.IsNotNull(modelState.Errors);
        }
开发者ID:sanyaade-mobiledev,项目名称:ASP.NET-Mvc-2,代码行数:7,代码来源:ModelStateTest.cs


示例3: SerializeModelState

 private static Dictionary<string, object> SerializeModelState(ModelState modelState) => new Dictionary<string, object>
                                                                                         {
                                                                                             ["errors"] = (from error in modelState.Errors
                                                                                                           select
                                                                                                               GetErrorMessage(error, modelState))
                                                                                                 .ToArray()
                                                                                         };
开发者ID:KatoTek,项目名称:Encompass,代码行数:7,代码来源:ModelStateExtensions.cs


示例4: BindModel

        public object BindModel(ControllerContext controllerContext,
                                        ModelBindingContext bindingContext)
        {
            ValueProviderResult valueResult = bindingContext.ValueProvider
                .GetValue(bindingContext.ModelName);
            ModelState modelState = new ModelState { Value = valueResult };
            object actualValue = null;
            try
            {
                if (valueResult != null)
                {
                    string valueToParse;

                    if (valueResult.AttemptedValue.Contains('.'))
                    {
                        valueToParse = valueResult.AttemptedValue.Replace('.', ',');
                    }
                    else
                    {
                        valueToParse = valueResult.AttemptedValue;
                    }
                    actualValue = Convert.ToDecimal(valueToParse, CultureInfo.CurrentCulture);
                }
            }
            catch (FormatException e)
            {
                modelState.Errors.Add(e);
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return actualValue;
        }
开发者ID:vladimirsbelajevs,项目名称:InventaraKontrolesSistema,代码行数:32,代码来源:DecimalModelBinder.cs


示例5: BindModel

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            var modelState = new ModelState { Value = valueResult };

            object actualValue = null;
            try
            {
                if (string.IsNullOrWhiteSpace(valueResult.AttemptedValue))
                    actualValue = bindingContext.ModelType == typeof(Date?) ? (object) null : default(Date);
                else
                    actualValue = new Date(Convert.ToDateTime(valueResult.AttemptedValue, CultureInfo.CurrentCulture));
            }
            catch (FormatException e)
            {
                var dateBinderMessage = GetBindingFailedMessge(bindingContext);

                if (!string.IsNullOrEmpty(dateBinderMessage))
                    modelState.Errors.Add(dateBinderMessage);
                else
                    modelState.Errors.Add(e);
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return actualValue;
        }
开发者ID:jd-pantheon,项目名称:Titan-Framework-v2,代码行数:26,代码来源:DateModelBinder.cs


示例6: BindModel

        public object BindModel(ControllerContext controllerContext,
            ModelBindingContext bindingContext)
        {
            ValueProviderResult valueResult = bindingContext.ValueProvider
                .GetValue(bindingContext.ModelName);
            ModelState modelState = new ModelState { Value = valueResult };
            object actualValue = null;
            try
            {
                //if with period use InvariantCulture
                if (valueResult.AttemptedValue.Contains("."))
                {
                    actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
                    System.Globalization.CultureInfo.InvariantCulture);
                }
                else
                {
                    //if with comma use CurrentCulture
                    actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
                    System.Globalization.CultureInfo.CurrentCulture);
                }

            }
            catch (FormatException e)
            {
                modelState.Errors.Add(e);
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return actualValue;
        }
开发者ID:anary,项目名称:kpmgtest,代码行数:31,代码来源:DecimalModelBinder.cs


示例7: BindModel

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            object actualValue = null;
            var modelState = new ModelState();
            try
            {
                var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
                if (string.IsNullOrEmpty(valueResult.AttemptedValue))
                {
                    return 0m;
                }
                modelState.Value = valueResult;

                try
                {
                    actualValue = Convert.ToDecimal(
                        valueResult.AttemptedValue.Replace(",", "."),
                        CultureInfo.InvariantCulture
                    );
                }
                catch (FormatException e)
                {
                    modelState.Errors.Add(e);
                }
            }
            catch (Exception e)
            {
                modelState.Errors.Add(e);
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return actualValue;
        }
开发者ID:AktivCo,项目名称:social,代码行数:33,代码来源:DecimalModelBinder.cs


示例8: CreateErrorModelState

        private static ModelState CreateErrorModelState(string field, string message)
        {
            var ms = new ModelState();
            ms.Errors.Add(message);

            return ms;
        }
开发者ID:simonb65,项目名称:SurveyTest,代码行数:7,代码来源:SurveyRunModelBinder.cs


示例9: BindModel

        public object BindModel(ControllerContext controllerContext,
           ModelBindingContext bindingContext)
        {
            var valueResult = bindingContext.ValueProvider
                .GetValue(bindingContext.ModelName);

            var modelState = new ModelState { Value = valueResult };

            object actualValue = null;

            if (!string.IsNullOrWhiteSpace(valueResult.AttemptedValue))
            {
                try
                {
                    actualValue = DateTime.ParseExact(valueResult.AttemptedValue,
                            SiteSettings.DateFormatJS.Replace("D", "d").Replace("Y", "y"), CultureInfo.InvariantCulture);
                }
                catch (FormatException e)
                {
                    modelState.Errors.Add(e);
                }
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return actualValue;
        }
开发者ID:huutoannht,项目名称:mart,代码行数:26,代码来源:DateTimeModelBinder.cs


示例10: BindModel

        public object BindModel(ControllerContext controllerContext,
            ModelBindingContext bindingContext)
        {
            ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            ModelState modelState = new ModelState { Value = valueResult };
            object actualValue = null;
            try
            {
                //Check if this is a nullable decimal and a null or empty string has been passed
                var isNullableAndNull = (bindingContext.ModelMetadata.IsNullableValueType && (string.IsNullOrEmpty(valueResult?.AttemptedValue)));

                //If not nullable and null then we should try and parse the decimal
                if (!isNullableAndNull && valueResult != null)
                {
                    decimal d;
                    if(decimal.TryParse(valueResult.AttemptedValue, NumberStyles.Any, CultureInfo.CurrentCulture, out d))
                        actualValue = d;
                    else
                        throw new Exception($"cannot parse decimal value {valueResult.AttemptedValue}");
                }
            }
            catch (FormatException e)
            {
                modelState.Errors.Add(e);
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return actualValue;
        }
开发者ID:stevesloka,项目名称:bvcms,代码行数:29,代码来源:DecimalModelBinder.cs


示例11: BindModel

        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            object actualValue = null;
            if (valueResult != null)
            {
                ModelState modelState = new ModelState { Value = valueResult };

                try
                {
                    string valToCheck = valueResult.AttemptedValue;
                    if (valToCheck == string.Empty)
                    {
                        actualValue = null;
                    }
                    else
                    {
                        actualValue = Convert.ToDecimal(valToCheck.Replace("$", string.Empty).Replace("¥", string.Empty), CultureInfo.InvariantCulture);
                    }
                }
                catch (FormatException e)
                {
                    modelState.Errors.Add(e);
                }

            }
            return actualValue;
        }
开发者ID:njmube,项目名称:CoffeeInvoice,代码行数:28,代码来源:CurrencyModelBinder.cs


示例12: BindModel

        public object BindModel(ControllerContext controllerContext,
            ModelBindingContext bindingContext)
        {
            var valueResult = bindingContext.ValueProvider
                .GetValue(bindingContext.ModelName);

            var modelState = new ModelState { Value = valueResult };

            object actualValue = null;

            try
            {
                var val = valueResult.AttemptedValue;
                if (string.IsNullOrWhiteSpace(val))
                {
                    val = "0";
                }

                actualValue = Convert.ToDecimal(val.Replace(" ", string.Empty), CultureInfo.CurrentCulture);
            }
            catch (FormatException e)
            {
                modelState.Errors.Add(e);
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return actualValue;
        }
开发者ID:huutoannht,项目名称:mart,代码行数:28,代码来源:DecimalModelBinder.cs


示例13: Create

        public async Task<ActionResult> Create([Bind(Include = "Id,Name,Type,Price")] Food food, HttpPostedFileBase file)
        {
            if (file == null)
            {
                var modelState = new ModelState();
                modelState.Errors.Add("The file is required! Please choose some file from your computer.");
                ModelState.Add("FileName", modelState);
            }
            if (ModelState.IsValid)
            {
                string path = Server.MapPath("~/Uploads/");
                string newFileName = Guid.NewGuid() + Path.GetExtension(file?.FileName);
                var url = HttpContext.ApplicationInstance.Request.Url;
                string host = $"{url.Scheme}://{url.Authority}";
                string filePath = Path.Combine(path, newFileName);
                file?.SaveAs(filePath);
                food.Id = Guid.NewGuid();
                food.Picture = Path.Combine(host + "/Uploads/", newFileName);
                db.Foods.Add(food);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }

            return View(food);
        }
开发者ID:Jurabek,项目名称:Restaurant,代码行数:25,代码来源:ManageFoodController.cs


示例14: BindModel

        //to add to application, in the global.ascx
        //protected void Application_Start()
        //{
        //ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
        /// <summary>
        /// Bind Model (Interface Methods)  Model Binder For Decimal's. Problem in MVC 3 where decimal data type doesnt come through to the controller for javascript calls
        /// </summary>
        /// <param name="ControllerContextToUse">Controller Context</param>
        /// <param name="BindingContext">Binding Context</param>
        /// <returns>Value Of Parameter</returns>
        public object BindModel(ControllerContext ControllerContextToUse, System.Web.Mvc.ModelBindingContext BindingContext)
        {
            //grab the value
            var ValueResult = BindingContext.ValueProvider.GetValue(BindingContext.ModelName);

            //set the model state
            var ModelStateToUse = new System.Web.Mvc.ModelState { Value = ValueResult };

            //value to return
            object ActualValue = null;

            try
            {
                //let's go and try to convert the value
                ActualValue = Convert.ToDecimal(ValueResult.AttemptedValue);
            }
            catch (FormatException e)
            {
                //if we can't convert set the model state error
                ModelStateToUse.Errors.Add(e);
            }

            //add the model and model state
            BindingContext.ModelState.Add(BindingContext.ModelName, ModelStateToUse);

            //return the actual value
            return ActualValue;
        }
开发者ID:dibiancoj,项目名称:ToracLibrary,代码行数:38,代码来源:DecimalModelBinder.cs


示例15: ValidationBanner

        public static MvcHtmlString ValidationBanner(this HtmlHelper htmlHelper, bool excludePropertyErrors, IDictionary<string, object> htmlAttributes)
        {
            if (htmlHelper == null) {
                throw new ArgumentNullException("htmlHelper");
            }

            FormContext formContext = htmlHelper.ViewContext.ClientValidationEnabled ?
                htmlHelper.ViewContext.FormContext :
                null;
            if (formContext == null && htmlHelper.ViewData.ModelState.IsValid) {
                return null;
            }

            IEnumerable<ModelState> modelStates = null;
            if (excludePropertyErrors) {
                ModelState ms;
                htmlHelper.ViewData.ModelState.TryGetValue(htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix, out ms);
                if (ms != null) {
                    modelStates = new ModelState[] { ms };
                }
            } else {
                modelStates = htmlHelper.ViewData.ModelState.Values;
            }

            string errorText = null;
            if (modelStates != null && modelStates.Any(x => x.Errors.Count > 0)) {
                errorText = modelStates.First(x => x.Errors.Count > 0)
                    .Errors.First().ErrorMessage;
            }

            TagBuilder errorLabelBuilder = new TagBuilder("strong");
            errorLabelBuilder.SetInnerText("ERROR: ");

            TagBuilder divBuilder = new TagBuilder("div");
            divBuilder.AddCssClass("alert alert-error");
            divBuilder.AddCssClass(htmlHelper.ViewData.ModelState.IsValid ?
                HtmlHelper.ValidationSummaryValidCssClassName :
                HtmlHelper.ValidationSummaryCssClassName);
            divBuilder.InnerHtml = errorLabelBuilder.ToString(TagRenderMode.Normal) +
                errorText;

            if (formContext != null) {
                if (htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled) {
                    if (!excludePropertyErrors) {
                        divBuilder.MergeAttribute("data-valmsg-banner", "true");
                    }
                } else {
                    divBuilder.GenerateId("validationSummary");
                    formContext.ValidationSummaryId = divBuilder.Attributes["id"];
                    formContext.ReplaceValidationSummary = !excludePropertyErrors;
                }
            }

            if (htmlAttributes != null) {
                divBuilder.MergeAttributes(htmlAttributes);
            }

            return MvcHtmlString.Create(divBuilder.ToString(TagRenderMode.Normal));
        }
开发者ID:jordanyaker,项目名称:mvc-4-boilerplate,代码行数:59,代码来源:HtmlHelperExtensions.cs


示例16: SerializeModelState

 private static Dictionary<string, object> SerializeModelState(ModelState modelState)
 {
     var result = new Dictionary<string, object>();
     result["errors"] = modelState.Errors
                                  .Select(error => GetErrorMessage(error, modelState))
                                  .ToArray();
     return result;
 }
开发者ID:danielkaradachki,项目名称:HomeWork,代码行数:8,代码来源:ModelStateExtensions.cs


示例17: GetErrorMessage

        private static string GetErrorMessage(ModelError error, ModelState modelState)
        {
            if (!IsNullOrEmpty(error.ErrorMessage))
                return error.ErrorMessage;

            return modelState.Value == null
                       ? error.ErrorMessage
                       : Format(CultureInfo.CurrentCulture, ValueNotValidForProperty, modelState.Value.AttemptedValue);
        }
开发者ID:KatoTek,项目名称:Encompass,代码行数:9,代码来源:ModelStateExtensions.cs


示例18: HasErrorMessage

 private bool HasErrorMessage(ModelState modelState, string errorMessage)
 {
     foreach (var error in modelState.Errors)
     {
         if (error.ErrorMessage == errorMessage)
             return true;
     }
     return false;
 }
开发者ID:bjeverett,项目名称:asp-net-mvc-unleashed,代码行数:9,代码来源:Movie2ControllerTests.cs


示例19: SetError

 public static void SetError(this ViewContext viewContext, string name, string errorValue)
 {
     var modelerror = new ModelState()
                      {
                          Value = new ValueProviderResult(errorValue, errorValue, new CultureInfo("en-AU"))
                      };
     modelerror.Errors.Add("Error");
     viewContext.ViewData.ModelState.Add(name, modelerror);
 }
开发者ID:eByte23,项目名称:SchoStack,代码行数:9,代码来源:ViewContextTestExtensions.cs


示例20: GetModelStateValue

        /// <summary>
        /// Returns the value in model state for the specified <paramref name="key"/> converted the to <paramref name="destinationType"/>, or null if it is not found.
        /// </summary>
        /// <param name="modelStateDictionary">The instance of <see cref="System.Web.Mvc.ModelStateDictionary"/> that is being extended.</param>
        /// <param name="key">The key.</param>
        /// <param name="destinationType">The value type.</param>
        /// <param name="modelState">An instance <see cref="System.Web.Mvc.ModelState"/>, or null if it is not found.</param>
        /// <returns>The value in model state.</returns>
        public static object GetModelStateValue( this ModelStateDictionary modelStateDictionary, string key, Type destinationType, out ModelState modelState )
        {
            if( !modelStateDictionary.TryGetValue( key, out modelState ) || modelState.Value == null )
            {
                return null;
            }

            return modelState.Value.ConvertTo( destinationType, null );
        }
开发者ID:john-t-white,项目名称:Hex,代码行数:17,代码来源:ModelStateDictionaryExtensions.cs



注:本文中的System.Web.Mvc.ModelState类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Mvc.MvcHtmlString类代码示例发布时间:2022-05-26
下一篇:
C# Mvc.ModelClientValidationRule类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap