在ASP.NET MVC中将错误添加到ModelState并重定向到同一页面不起作用。

huangapple go评论76阅读模式
英文:

Adding an error to ModelState and redirecting to the same page not working in ASP.NET MVC

问题

我有一个网站在本地服务器上,用户可以向我发送消息。我从表单的模态框中捕获用户的姓名、电子邮件和消息。
现在我有一个控制器,检查该电子邮件是否已存在,并获取该电子邮件地址最后一次向服务器发送消息的时间,然后计算如果时间间隔小于30分钟,就向Index页面模型添加一个模型错误,并重定向到它。

在Index页面的模型中,我检查模型状态是否有效,并显示错误消息您只允许每30分钟发送一次消息,并将该错误显示在一个span标签内,但在我的情况下ModelState.IsValid()返回true,为什么会这样,我已经进行了修改。我期望用户在尝试打开模态框后在重定向后看到以红色显示的消息。
处理请求的控制器方法如下:

public IActionResult GetAction([FromForm]string Name, [FromForm] string Email, [FromForm] string Query)
{
    // 确保同一用户在发送新消息之前需要等待30分钟
    // 检查该电子邮件是否已发送短信
    if(_dbCtx.ClientMessages.ToList().Any(x => x.Email == Email)){
        // 这意味着用户现在发送了一条消息,获取他最后一次发送的时间
        var date = _dbCtx.ClientMessages.FirstOrDefault(x => x.Email == Email).Time;
        var minElapsed = TimeSpan.FromMinutes(DateTime.Now.Subtract(date).TotalMinutes);
        if (minElapsed.TotalMinutes < 30)
        {
            // 将此错误添加到Index页面模型
            ModelState.AddModelError("", "您只允许每30分钟发送一条新消息");
            // 重定向到Index页面
            return RedirectToPage("/Index");
        }
    }
}

然后在index.cshtml中,我这样检查状态:

<div class="modal-header">
    <h4 class="modal-title" id="myModalLabel">Contact Us</h4>
    @if (!ViewData.ModelState.IsValid)
    {
        // 在span中显示错误消息
        <span id="error-message" class="text-danger">@Html.ValidationSummary(false)</span>
    }
    <button type="button" class="close" onclick="closeModal()" aria-hidden="true">&times;</button>
</div>
英文:

I have a website on a local server where users can send me a message. I capture the name, email and the message from the user from a modal on my form.
Now I have a controller that checks if that email already exists and gets the last time that email address posted a message to the server and computes if the interval is less than 30 minutes then adds a Model error to the Index Page model and redirects to it.

In the model of the Index Page, I check if the model state is valid and display the error you are only allowed to send a message every 30 minutes and display that error inside a span tag but the ModelState.IsValid() is returning true in my case, why is this when I have already modified it. Am expecting the user to be shown the message in red after user attempts to open the modal on redirect.
The controller method that handles the request is this

public IActionResult GetAction([FromForm]string Name, [FromForm] string Email, [FromForm] string Query)
        {
            //make sure the same user allows 30 minutes to elapse before sending a new message
            //check if that email has already sent an sms
            if(_dbCtx.ClientMessages.ToList().Any(x=&gt; x.Email == Email)){
                //this means the user posted a message now, get the last time he posted
                var date = _dbCtx.ClientMessages.FirstOrDefault(x=&gt; x.Email == Email).Time;
                var minELAPSED = TimeSpan.FromMinutes(DateTime.Now.Subtract(date).TotalMinutes);
                if (minELAPSED.TotalMinutes &lt; 30)
                {
                    //add this error to the index page model
                    ModelState.AddModelError(&quot;&quot;, &quot;You are only allowed to send a new message once every 30 minutes&quot;);
                    //redirect to index 
                    return RedirectToPage(&quot;/Index&quot;);
                }
            }

and then inside the index.cshtml,I check for the state like this.

   &lt;div class=&quot;modal-header&quot;&gt;
                &lt;h4 class=&quot;modal-title&quot; id=&quot;myModalLabel&quot;&gt;Contact Us&lt;/h4&gt;
                @if (!ViewData.ModelState.IsValid)
                {
                    //display the error message in the span
                    &lt;span id=&quot;error-message&quot; class=&quot;text-danger&quot; &gt;@Html.ValidationSummary(false)&lt;/span&gt;
                }
                &lt;button type=&quot;button&quot; class=&quot;close&quot; onclick=&quot;closeModal()&quot; aria-hidden=&quot;true&quot;&gt;&amp;times;&lt;/button&gt;
            &lt;/div&gt;

答案1

得分: 1

因为您正在重定向,所以ModelState丢失。您可以不使用TempData吗?

public IActionResult GetAction([FromForm]string Name, [FromForm] string Email, [FromForm] string Query)
{
    if(_dbCtx.ClientMessages.ToList().Any(x=&gt; x.Email == Email)){
        var date = _dbCtx.ClientMessages.FirstOrDefault(x=&gt; x.Email == Email).Time;
        var minELAPSED = TimeSpan.FromMinutes(DateTime.Now.Subtract(date).TotalMinutes);
        if (minELAPSED.TotalMinutes &lt; 30)
        {
            TempData[&quot;ErrorMessage&quot;] = &quot;您只能每30分钟发送一条新消息&quot;;
            return RedirectToPage(&quot;/Index&quot;);
        }
    }
    // 返回其他内容
}
&lt;div class=&quot;modal-header&quot;&gt;
    &lt;h4 class=&quot;modal-title&quot; id=&quot;myModalLabel&quot;&gt;联系我们&lt;/h4&gt;
    @if (TempData[&quot;ErrorMessage&quot;] != null)
    {
        &lt;span id=&quot;error-message&quot; class=&quot;text-danger&quot;&gt;@TempData[&quot;ErrorMessage&quot;]&lt;/span&gt;
    }
    &lt;button type=&quot;button&quot; class=&quot;close&quot; onclick=&quot;closeModal()&quot; aria-hidden=&quot;true&quot;&gt;&amp;times;&lt;/button&gt;
&lt;/div&gt;
英文:

Because you are redirecting, the ModelState is lost. Can you not use TempData?

public IActionResult GetAction([FromForm]string Name, [FromForm] string Email, [FromForm] string Query)
{
    if(_dbCtx.ClientMessages.ToList().Any(x=&gt; x.Email == Email)){
        var date = _dbCtx.ClientMessages.FirstOrDefault(x=&gt; x.Email == Email).Time;
        var minELAPSED = TimeSpan.FromMinutes(DateTime.Now.Subtract(date).TotalMinutes);
        if (minELAPSED.TotalMinutes &lt; 30)
        {
            TempData[&quot;ErrorMessage&quot;] = &quot;You are only allowed to send a new message once every 30 minutes&quot;;
            return RedirectToPage(&quot;/Index&quot;);
        }
    }
    // return something else 
}
&lt;div class=&quot;modal-header&quot;&gt;
    &lt;h4 class=&quot;modal-title&quot; id=&quot;myModalLabel&quot;&gt;Contact Us&lt;/h4&gt;
    @if (TempData[&quot;ErrorMessage&quot;] != null)
    {
        &lt;span id=&quot;error-message&quot; class=&quot;text-danger&quot;&gt;@TempData[&quot;ErrorMessage&quot;]&lt;/span&gt;
    }
    &lt;button type=&quot;button&quot; class=&quot;close&quot; onclick=&quot;closeModal()&quot; aria-hidden=&quot;true&quot;&gt;&amp;times;&lt;/button&gt;
&lt;/div&gt;

huangapple
  • 本文由 发表于 2023年6月26日 15:48:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76554589.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定