ASP.NET MVC 3 HtmlHelper.Textbox用途的ModelState作为价值的来源? [英] ASP.NET MVC 3 HtmlHelper.Textbox Uses ModelState as a source for value?

查看:100
本文介绍了ASP.NET MVC 3 HtmlHelper.Textbox用途的ModelState作为价值的来源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本框,我修剪服务器端的价值在视图模型的setter和验证修整值是present:

I have a textbox that I am trimming the value of server side in the viewModel's setter and verifying that the trimmed value is present:

    <Required()>
    Public Property Name As String
        Get
            Return Me.mName
        End Get
        Set(value As String)
            Me.mName = value.Trim()
        End Set
    End Property

在控制器中,我检查,看看是否的ModelState是无效的,如果是这样,我再次显示视图:

In the controller, I check to see if the ModelState is invalid, and if it is, I show the view again:

    If (Not ModelState.IsValid) Then
        Return View("Locations", viewModel)
    End If

在那里修整值为空的情况下,我重新显示形式提供给用户。在这一点上,非修剪值被放置到文本框中。我更preFER修剪值。

In situations where the trimmed value is blank, I re-display the form to the user. At this point, the non-trimmed values are put into the textbox. I would much prefer the trimmed value.

我一直在寻找通过MVC源码code,而且我发现,在InputHelper功能(由Html.Textbox()使用,位于InputExtensions.cs)在code被检查的ModelState一个点的值,并且如果存在,更换控制器提供的值

I was looking through the MVC sourcecode, and I found that at one point in the InputHelper function (used by Html.Textbox(), located in InputExtensions.cs) the code was checking the ModelState for the value, and if it existed, replacing the controller-supplied value.

    string attemptedValue = (string)htmlHelper.GetModelStateValue(name, typeof(string));
    tagBuilder.MergeAttribute("value", attemptedValue ?? ((useViewData) ? htmlHelper.EvalString(name) : valueParameter), isExplicitValue);

我知道我可以在控制器清除的ModelState解决这个问题,但我只是想知道,为什么MVC开发者选择在该ModelState中的值取代视图模型值。

I realize that I could fix this by clearing the ModelState in the controller, but I'm just wondering why the MVC Developers chose to have the values in the ModelState supersede the view model values.

推荐答案

这是设计成这样,因为假设是,如果你没有一个职位后重定向到另一个观点..因此,重定向后得到的模式,则有是理想的一个错误,并且当前发布的值将被显示给用户为他们因而固定为什么它们从的ModelState拉动。您可以使用ModelState.Clear这个工作,但保留了设计的初衷。

This was designed this way because the assumption is if you are not redirecting to another view after a post .. Hence the post-redirect-get pattern, then there was ideally an error and the current posted values would be shown back to the user for them to fix hence why they are pulled from modelstate. You can ModelState.Clear to work with this but keep that design in mind.

这篇关于ASP.NET MVC 3 HtmlHelper.Textbox用途的ModelState作为价值的来源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆