我有这个课程:
public class GroupMetadata
{
[HiddenInput(DisplayValue = false)]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
[MetadataType(typeof(GrupoMetadata))]
public partial class Group
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这个动作:
[HttpPost]
public ActionResult Edit(Group group)
{
if (ModelState.IsValid)
{
// Logic to save
return RedirectToAction("Index");
}
return View(group);
}
Run Code Online (Sandbox Code Playgroud)
这是我的观点:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Group>" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% …
Run Code Online (Sandbox Code Playgroud) 基本上我无法显示从控制器返回的模型状态错误(WebApi).使用MVC4,jQuery和淘汰赛.希望你能从下面看到我想要实现的目标 - 提前感谢.
视图:-
<div class="editor-field">
@Html.TextBoxFor(model => model.CostCode,
new
{
placeholder = "cost/budget code",
data_bind = "value: CostCode"
})
</div>
<div>
@Html.ValidationMessageFor(model => model.CostCode)
</div>
Run Code Online (Sandbox Code Playgroud)
淘汰视图模型做帖子/提交: -
if (validator.valid())
{
console.log('is valid');
$.ajax({
url: '/api/Booking/CompleteBooking',
type: 'POST',
dataType: 'json',
data: ko.mapping.toJS(self),
error: function (jqXHR) {
extractErrors(jqXHR, validator);
},
success: function (data) {
console.log(data);
}
});
}
function extractErrors(jqXhr, validator)
{
var data = $.parseJSON(jqXhr.responseText),
errors = { };
$.each(data.ModelState, function (i, item) {
errors[i] = item;
});
console.log(errors);
validator.showErrors(errors); …
Run Code Online (Sandbox Code Playgroud) 我需要替换模型状态资源(到另一种语言).
我已经看到了上述问题的一些答案,但不幸的是我无法让它发挥作用.任何详细的答案或例子都会受到批评.
谢谢.
我们需要在一些逻辑中迭代模型的属性以自动绑定属性,并希望扩展功能以在C#4.0中包含新的数据注释.
目前,我基本上遍历所有ValidationAttribute实例中的每个属性加载并尝试使用Validate/IsValid函数进行验证,但这似乎对我没有用.
作为一个例子,我有一个模型,如:
public class HobbyModel
{
[Required(AllowEmptyStrings = false, ErrorMessage = "Do not allow empty strings")]
[DisplayName("Hobby")]
[DataType(DataType.Text)]
public string Hobby
{
get;
set;
}
}
Run Code Online (Sandbox Code Playgroud)
检查属性的代码是:
object[] attributes = propertyInfo.GetCustomAttributes(true);
TypeConverter typeConverter =
TypeDescriptor.GetConverter(typeof(ValidationAttribute));
bool isValid = false;
foreach (object attr in attributes)
{
ValidationAttribute attrib = attr as ValidationAttribute;
if (attrib != null)
{
attrib.Validate(obj, propertyInfo.Name);
}
}
Run Code Online (Sandbox Code Playgroud)
我调试了代码,模型确实有3个属性,其中2个是从ValidationAttribute派生的,但是当代码通过Validate函数(带有空值或空值)时,它会按预期抛出异常.
我期待我做一些愚蠢的事情,所以我想知道是否有人使用过这个功能并且可以提供帮助.
先谢谢,杰米
asp.net modelstate validationattribute data-annotations asp.net-mvc-3
我们假设我有一个由3个其他ViewModel组成的ViewModel.一个包含项目列表,另一个包含具有[Required]属性的类的实例,然后包含另一个其他项的列表.
如果用户从两个列表中的任何一个列表中选择一个项目,我不希望第二个对象上的[Required]属性导致ModelState无效,因为如果用户选择其中一个项目,它们将不会需要使用[Required]属性填写表单.
我怎么解决这个问题?
当我尝试将图像上传到我的MVC控制器操作并且存在验证错误时,我必须单击每个按钮并再次查找我的所有文件.
如果我有一个包含的视图
<input type="file" id="file0" name="Files[0]" />
<input type="file" id="file1" name="Files[1]" />
Run Code Online (Sandbox Code Playgroud)
和控制器动作一样
public ActionResult Create(ModelClass model, IEnumerable<HttpPostedFileBase> Files)
{
if(ModelState.IsValid)
{
//do work
if(PhotoValidation.IsValid(Files))
{
//do work
}
else
{
ModelState.AddModelError("","Photos not valid");
}
}
return view(model); // Way to return photos back to the view on modelstate error?
}
Run Code Online (Sandbox Code Playgroud)
文件很好地发布到服务器,但是如果有模型验证错误,有没有办法返回模型和文件,以便用户不必再次上传它们?
我不明白为什么ModelState.isValid会以各种方式给我.我在电子邮件中设置了一些返回true并且我在空字段中输入,它也返回true.我的问题是,当该字段为空时,如果我写了这封电子邮件,我该怎么办?
我有下一个视图文件:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div style="padding-top:5px;clear:both;"></div>
<% using (Html.BeginForm()) { %>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Email usuario</legend>
<div class="editor-field">
<%: Html.TextBoxFor(m => m.Email) %>
<%: Html.ValidationMessageFor(m => m.Email) %>
</div>
<input type="submit" value="Enviar Email" />
</fieldset>
<% } %>
<div style="padding-top:5px;clear:both;"></div>
</asp:Content>
Run Code Online (Sandbox Code Playgroud)
控制器是:
//
// GET: /Account/EmailRequest
public ActionResult EmailRequest()
{
return View();
}
[HttpPost]
public ActionResult EmailRequest(string email)
{
if (ModelState.IsValid)
{
// save to db, for instance
return RedirectToAction("AnotherAction");
}
return View();
}
Run Code Online (Sandbox Code Playgroud)
我的模型类是:
using System; …
Run Code Online (Sandbox Code Playgroud) 我遇到了一个问题,我正在尝试确定哪个ValidationAttribute返回了特定的ModelError.我的web api中有一个端点,它采用的模型如:
public class MyClass
{
[Required]
[Range(0, 3)]
public int? Number { get; set; }
[Required]
[Range(0, 3)]
public int? NumberTwo { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
以及用于检查ModelState是否有效的过滤器;
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
IEnumerable<ModelError> errors = actionContext.ModelState.Values.SelectMany(s => s.Errors);
// ...
}
}
}
Run Code Online (Sandbox Code Playgroud)
我看到ModelError有两个属性; ErrorMessage是string类型,Exception是Exception类型.我想要一种强类型的方法来确定哪个ValidationAttribute [Required]或[Range(0,3)]返回错误响应而不进行字符串操作.有没有办法使用我不熟悉的这些属性返回自定义属性?
如果客户要发布一个模型,如
{
"NumberTwo":10
}
Run Code Online (Sandbox Code Playgroud)
最终目标是从API产生响应,如下所示;
{
"supportCode" : "1234567890",
"errors" : [{
"code" : "Missing",
"message" : "The Number field is required."
}, …
Run Code Online (Sandbox Code Playgroud) 如何在 WEB Api .net 框架中将模型状态键设置为驼峰式大小写。
我使用 JsonProperty 属性将属性名称设置为驼峰式大小写。现在我希望模型状态与 json (camel case) 相同,我该如何实现?
c# .net-framework-version json.net modelstate asp.net-web-api2
我的 .Net 5./ASP.Net MVC 应用程序中有一个“编辑”页面。如果ModelState.IsValid
是“false”,我想在拒绝整个页面之前检查各个错误。
问题:如何获取列表中无效项目的“名称” ModelState
?
例如:
处理程序方法:public async Task<IActionResult> OnPostAsync()
if (!ModelState.IsValid)
: “错误的”
this.ModelState.Values[0]: SubKey={ID}, Key="ID", ValidationState=无效 Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateEntry {Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary.ModelStateNode}
代码:
foreach (ModelStateEntry item in ModelState.Values)
{
if (item.ValidationState == ModelValidationState.Invalid)
{
// I want to take some action if the invalid entry contains the string "ID"
var name = item.Key; // CS1061: 'ModelStateEntry 'does not contain a definition for 'Key'
...
Run Code Online (Sandbox Code Playgroud)
问题:如何从每个无效的 ModelState“值”项中读取“键”???
解决
我的基本问题是迭代“ModelState.Values”。相反,我需要迭代“ModelState.Keys”才能获取所有必需的信息。
解决方案1)
foreach (KeyValuePair<string, ModelStateEntry> modelStateDD in …
Run Code Online (Sandbox Code Playgroud) modelstate ×10
c# ×4
asp.net-mvc ×3
validation ×2
.net-5 ×1
asp.net ×1
attributes ×1
file ×1
jquery ×1
json.net ×1
knockout.js ×1
resources ×1
viewmodel ×1