操作参数始终不为空
代码如下:
public class MessagesController
{
public virtual ActionResult Compose(ComposeMessageViewModel composeMessageViewModel = null)
{
if (composeMessageViewModel == null)
{
// never executed as composeMessageViewModel is always not null
composeMessageViewModel = new ComposeMessageViewModel();
}
return View(composeMessageViewModel);
}
}
ComposeMessageViewModel 的定义
public class ComposeMessageViewModel
{
[DisplayName("To:")]
[NotEmpty] //custom ValidationAttribute
public IEnumerable<MessageRecipientViewModel> Recipients { get; set; }
[DisplayName("Subject:")]
public string Subject { get; set; }
public string Body { get; set; }
}
问题是,当我导航到 /Messages/Compose
(没有查询字符串,没有表单参数)时,我期望参数为 null,这样就不会会发生验证错误,但它是一个实际对象,其所有字段/属性都设置为默认值。
这是不可取的,因为它会导致执行模型验证,而实际上不应该执行模型验证,因为尚未输入任何内容!
此类没有设置自定义 ModelBinder,默认的 ModelBinder 也没有更改。
搞什么?
Here's the code:
public class MessagesController
{
public virtual ActionResult Compose(ComposeMessageViewModel composeMessageViewModel = null)
{
if (composeMessageViewModel == null)
{
// never executed as composeMessageViewModel is always not null
composeMessageViewModel = new ComposeMessageViewModel();
}
return View(composeMessageViewModel);
}
}
And the definition of ComposeMessageViewModel
public class ComposeMessageViewModel
{
[DisplayName("To:")]
[NotEmpty] //custom ValidationAttribute
public IEnumerable<MessageRecipientViewModel> Recipients { get; set; }
[DisplayName("Subject:")]
public string Subject { get; set; }
public string Body { get; set; }
}
The problem is, when I navigate to /Messages/Compose
(no query string, no form parameters), I'm expecting the parameter to be null so that no validation errors would occur, but it's an actual object with all its fields/properties set to default values.
This is undesirable as it causes the validation for the model to be executed, when it should not be as nothing has been entered yet!
There's no custom ModelBinder set for this class, and the default ModelBinder has not been changed.
WTF?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是你的代码正在做的事情 - 创建一个具有默认值的对象吗?
Isn't that what your code is doing - creating an object with default values?
正确答案:PEBKAC。我最初有一个 Send 操作,如果验证失败,我想我必须出于某种原因重定向到 Compose 操作,而不是仅使用适当的 ViewModel 返回适当的视图。嘟嘟嘟嘟。 :)
The true answer: PEBKAC. I originally had a Send action which, if validation failed, I thought I would have to redirect to the Compose action for some reason instead of just returning the appropriate view with the appropriate ViewModel. Duuuuuuuh. :)