asp.net-mvc 成功后清除字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10855021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:59:45  来源:igfitidea点击:

Clear fields after success

asp.net-mvc

提问by MuriloKunze

I have a page with 2 input type=text..

我有一个带有 2 个输入类型 = 文本的页面。

@model MVC3.ViewModel.TalkToUsVM

@using (Html.BeginForm())
{
    <ul>
        <li>@Html.TextBoxFor(m => m.TalkToUsRequest.Name)</li>
        <li>@Html.TextBoxFor(m => m.TalkToUsRequest.Email)</li>
    </ul>

    <input type="submit" value="Save"/>
}

in my controller I do this:

在我的控制器中,我这样做:

[HttpPost]
public ActionResult Create(TalkToUsRequest talkToUsRequest)
{
    var vm = new TalkToUsVM();

    if (TryValidateModel(talkToUsRequest))
    {
        vm.Result = "Success";

        return View("Create",vm);
    }

    vm = new TalkToUsVM
    {
        Result = "Errrooooooor",
        TalkToUsRequest = talkToUsRequest
    };

    return View(vm);
}

so the problem.. when my model is valid, I set the result to "Success" and in this point vm.TalkToUsRequest is null.. but when page is rendered, all fields are with the same value that when I submited.. even I setting vm.TalkToUsRequest = null!! How can I clear this fields?

所以问题..当我的模型有效时,我将结果设置为“成功”,此时 vm.TalkToUsRequest 为空..但是当页面呈现时,所有字段都具有与我提交时相同的值..甚至我设置 vm.TalkToUsRequest = null!! 如何清除这些字段?

回答by Lav

So in this scenario you have to clear your model state if you return back to the same view. Try following:

因此,在这种情况下,如果您返回到同一视图,则必须清除模型状态。尝试以下操作:

    ModelState.Clear();
    return View(vm);
}

回答by abhijeet abanave

Your answer :

你的答案 :

TryUpdateModel(yourmodelname);

and it will update your view state

它会更新你的视图状态

and if you also want to clear all Modelstate.error at the same time you can also use :

如果您还想同时清除所有 Modelstate.error,您还可以使用:

 ModelState.Clear();