【问题标题】:Clearing text box fields on a page in MVC在 MVC 中清除页面上的文本框字段
【发布时间】:2011-02-03 14:13:23
【问题描述】:

出于某种原因,应该是一个简单的问题却难倒我。我是 MVC 新手,所以应该解释一下。

我正在尝试在输入提交后清除页面上的所有字段。

我在示例中看到了以下代码,但不知道该放在哪里。我在我的 PersonModel.vb 中尝试过它并引发错误。我在我的存储库中尝试了它,在那里我保留了我的 subs 和函数,它每次都会在单词 ModelState 和 ValueProvierResult 上抛出错误。

ModelState.SetModelValue("Key", new ValueProviderResult(null, string.Empty, CultureInfo.InvariantCulture))

有人可以为我提供一些建议以清除页面上的字段(文本框)吗?我对 MVC 很陌生,可以使用一些助手。

谢谢

长宽

这里是代码......

<HttpPost(), MvcReCaptcha.CaptchaValidator()> _
Function Nominate(ByVal m As NominationModel, ByVal captchaValid As Boolean) As ActionResult

    Dim db = New ChampionTrees.Common.DataAccess.ChampionTreesRepository With {.UserName = "SYSTEM"}
    BindNominateDdls(db)

    Dim addPost As Boolean = False
    If (Request.Form("addNominator") <> Nothing) Then
        m.People.Add(New PersonModel With {.Indicator = PersonIndicator.Nominator})
        addPost = True
    ElseIf Request.Form("addOwner") <> Nothing Then
        m.People.Add(New PersonModel With {.Indicator = PersonIndicator.Owner})
        addPost = True
    Else
        For Each f In Request.Form.Keys
            If f.ToString.StartsWith("deletePerson") Then

                Dim idx = f.ToString.IndexOf("n")
                m.People.RemoveAt(Integer.Parse(f.ToString.Substring(idx + 1, f.ToString.Length - (idx + 1))))
                addPost = True
                Exit For

            End If
        Next
    End If

    If addPost Then

        For Each v In ModelState.Values.AsEnumerable()
            v.Errors.Clear()
        Next

        Return View(m)

    End If

    If m.Tree.Id < 0 AndAlso String.IsNullOrEmpty(m.OtherName) Then

        Dim err As String = "Either a Common, Scientific, or Other Name must be provided."
        ModelState.AddModelError("Tree.Id", err)
        ModelState.AddModelError("OtherName", err)

    End If

    If String.IsNullOrEmpty(m.Measurement.CountyForester) = _
        String.IsNullOrEmpty(m.Measurement.OtherCountyForester) Then

        Dim err As String = "A County Forester must be selected or entered (but not both)."
        ModelState.AddModelError("Measurement.CountyForester", err)
        ModelState.AddModelError("Measurement.OtherCountyForester", err)

    End If

    Dim i As Integer = 0
    For Each p As PersonModel In m.People

        If String.IsNullOrEmpty(p.EmailAddress) AndAlso _
            (p.Phone.Phone1 Is Nothing Or p.Phone.Phone2 Is Nothing Or p.Phone.Phone3 Is Nothing) Then

            ModelState.AddModelError(String.Format("People[{0}].Phone", i), "Either an E-mail Address or Phone number must be provided.")
            ModelState.AddModelError(String.Format("People[{0}].Phone.Phone1", i), "")
            ModelState.AddModelError(String.Format("People[{0}].Phone.Phone2", i), "")
            ModelState.AddModelError(String.Format("People[{0}].Phone.Phone3", i), "")
            ModelState.AddModelError(String.Format("People[{0}].EmailAddress", i), " ")

        Else

            Dim int As Integer = 0
            Dim err As Boolean = False

            If Not p.Phone.Phone1 Is Nothing AndAlso _
                            (p.Phone.Phone1.Length <> 3 Or Not Integer.TryParse(p.Phone.Phone1, Int)) Then

                ModelState.AddModelError(String.Format("People[{0}].Phone.Phone1", i), "")
                err = True
            End If
            If Not p.Phone.Phone2 Is Nothing AndAlso _
                            (p.Phone.Phone2.Length <> 3 Or Not Integer.TryParse(p.Phone.Phone2, int)) Then

                ModelState.AddModelError(String.Format("People[{0}].Phone.Phone2", i), "")
                err = True
            End If
            If Not p.Phone.Phone3 Is Nothing AndAlso _
                (p.Phone.Phone3.Length <> 4 Or Not Integer.TryParse(p.Phone.Phone3, int)) Then

                ModelState.AddModelError(String.Format("People[{0}].Phone.Phone3", i), "")
                err = True
            End If

            If err Then ModelState.AddModelError(String.Format("People[{0}].Phone", i), "Phone Number is not numeric.")

        End If

        If m.OwnershipType = Ownership.Public AndAlso _
            p.Indicator = PersonIndicator.Owner AndAlso _
            p.ParcelName Is Nothing Then
            ModelState.AddModelError(String.Format("People[{0}].ParcelName", i), "The Parcel Name field is required for public nominations.")
        End If

        i += 1

    Next

    If Not m.UseNominatorsAsOwners AndAlso _
        (From e In m.People Where e.Indicator = PersonIndicator.Owner Select e).Count = 0 Then
        ModelState.AddModelError("UseNominatorsAsOwners", "At least one Owner is required.")
    End If

    If Files.Count > 0 AndAlso Not m.ElectronicUseAgreement Then
        ModelState.AddModelError("ElectronicUseAgreement", "The Electronic Use Agreement must be agreed to.")
    End If

    If Not captchaValid Then
        ModelState.AddModelError("ReCaptcha", "You did not type the verification word correctly. Please try again.")
    End If

    If ModelState.IsValid Then

        ' load our uploads from session
        For Each f In Files
            f.Value.Viewable = m.ElectronicUseAgreement
            m.Uploads.Add(f.Value)
        Next

        ' insert the nomination into the db
        db.InsertNomination(m)

        ViewData("message") = "Nomination has been submitted"

    End If

    ModelState.Clear()
    Return View(m)

【问题讨论】:

    标签: asp.net-mvc field


    【解决方案1】:

    您好,您应该可以使用:ModelState.Clear(),当您返回查看时,所有以前输入的数据都将被清除。

    编辑:

    下面是一些示例代码:

    public ActionResult Index()
    {
      return View();
    }
    
    [HttpPost]
    public ActionResult Index(FormCollection collection)
    {
      // This will clear whatever form items have been populated
      ModelState.Clear();
    
      return View();
    }
    

    更新 2:

    在您的代码中,您正在清除 ModelState,但是您将模型(您已将其称为 m)传递回您的视图,然后您的视图将选择此模型并显示其属性。

    例如,如果我有一个接受名字和姓氏的页面,当我发布时我想将其添加到数据库中,然后返回相同的视图但为我的下一个请求为空,我的代码将类似于:

    public ActionResult Index()
    {
      return View();
    }
    
    [HttpPost]
    public ActionResult Index(Person p)
    {
      if (ModelState.IsValid)
      {
        // This will clear whatever form items have been populated
        ModelState.Clear();
        // Here I'm just returning the view I dont want a model being passed
        return View();
      }
    
      // Here I'm returning the model as there's an error and the user needs to see
      // what has been entered.
      return View(p);
    }
    

    【讨论】:

    • 当我尝试它说“ModelState”未声明。我应该在哪里使用该代码?
    • 我什至在 aspx 页面上试过,它说 ModelState 没有 Clear() 方法......
    • 我已经更新了一些示例代码 - 如果您仍然不明白,您可以发布您的代码。谢谢
    • 我让它接受 ModelState.Clear()。我需要为其添加导入,但它没有清除表单。没有任何改变。
    • 你能发布你的控制器/动作吗?
    【解决方案2】:

    或者,如果 ModelState 有效,您可以像这样重定向回 Get Action:

    public ActionResult Index()
    {
       return View();
    }
    
    [HttpPost]
    public ActionResult Index(Person p)
    {
      if (ModelState.IsValid)
      {
        // do work and finally back to Get Action
        return RedirectToAction("Index");
      }
    
      return View(p);
    }
    

    【讨论】:

    • ModelState.Clear() 对我不起作用。但确实如此。
    • 谢谢,它解决了我的问题 RedirectToAction("Index") 而不是 View();
    【解决方案3】:

    你是否可以使用 jQuery 并做类似的事情

    $(document).ready(function(){
        $("input").each(function(){
             $(this).val("");
        });
    });
    

    也许将其包装成某种形式是发布的 Razor 代码。

    【讨论】:

    • 我想知道 jQuery.... 还没有尝试过。我在页面的 OnLoad 事件中考虑了一些代码,但不确定您是否可以使用 MVC 做到这一点。
    【解决方案4】:

    在 Jquery 中

    $("#btnID").click(function () {
        $("input[type=text]").val("");
    
    });
    

    modelstate.clear()提交成功后

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-12
      相关资源
      最近更新 更多