简体   繁体   English

动作参数始终不为null

[英]Parameter for action always not null

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 以及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. 问题是,当我导航到/Messages/Compose (没有查询字符串,没有表单参数)时,我期望参数为null,这样就不会发生验证错误,但这是一个包含所有字段/属性的实际对象设置为默认值。

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. 没有为此类设置自定义ModelBinder,并且默认ModelBinder尚未更改。

WTF? WTF?

Isn't that what your code is doing - creating an object with default values? 这不是您的代码在做什么-创建具有默认值的对象吗?

   if (composeMessageViewModel == null)
   {
        composeMessageViewModel = new ComposeMessageViewModel();
   }

The true answer: PEBKAC. 真正的答案: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. 我最初有一个Send操作,如果验证失败,我认为出于某种原因我将不得不重定向到Compose操作,而不是仅仅使用适当的ViewModel返回适当的视图。 Duuuuuuuh. Duuuuuuuh。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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