asp.net-mvc - 清除 MVC 4 Razor View 中的所有字段 : Loading and after Back to Page

标签 asp.net-mvc asp.net-mvc-4 razor field

为了在加载 MVC4 Razor 时将其上的所有字段设为空(例如第一次加载或再次返回页面后),最有效的方法是什么?如果可能的话,请您在 Razor 属性的帮助下向我建议一种方法,而不是使用 Javascript/jQuery。

最佳答案

弄清楚您要做什么有点困难,但让我们看看我是否可以提供帮助。

首先,如果您只是想在表单发布后清除表单的值,您可以这样做:

[HttpPost]
public ActionResult Index(ViewModel model)
{
    ModelState.Clear();
    model = new ViewModel();

    return View(model);
}

只需新建一个 ViewModel还不够,因为ModelState字典将尝试用旧值重新填充表单。这可以满足您的需求,但并没有真正利用 MVC 来做您想做的事情。

更好的方法是重定向回用于显示表单的操作。像这样的东西:
public ActionResult Create()
{
    var model = new ViewModel();

    return View(model);
}

这只是将一个空模型传递给您的表单。一旦用户填写了表单并将其发送回服务器,您就可以像这样处理它:
[HttpPost]
public ActionResult Create(ViewModel model)
{
    if (ModelState.IsValid)
    {
        // Form data is valid so redirect back to display the form again
        return RedirectToAction("Create");
    }

    // If we get here, redisplay the form with the fields filled in
    // and errors shown
    return View(model);
}

关于asp.net-mvc - 清除 MVC 4 Razor View 中的所有字段 : Loading and after Back to Page,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19659048/

相关文章:

asp.net-mvc - 在 MVC 中删除 DropDownList 上的空白条目

.net - MVC 4 在前端隐藏客户端 ID 的最佳实践

json - 内容类型 'application/json; charset=utf-8' 不是预期的类型 'text/xml; charset=utf-8'

asp.net-mvc - 难以启动基本单元测试(我书中的示例——SportsStore)

c# - View 中的模型无法绑定(bind)到 ASP.NET MVC4 中 Controller 中的操作

rest - 带有 DotNetOpenAuth 的 ASP.NET Web API

c# - foreach 内下拉菜单的选定值 - Razor

asp.net-mvc - 如何将 HTML 表单转换为 C# 以用于 PayPal 订阅

asp.net-mvc-3 - 仅在启用 javascript 时隐藏元素

javascript - 将 JQuery ajax GET 转换为 POST