【问题标题】:clear the text area in post method清除 post 方法中的文本区域
【发布时间】:2017-02-21 01:13:30
【问题描述】:

我有一个表格。在该表单中,我有一个文本区域属性。单击提交按钮后,我想在同一页面中显示一些视图包值,同时我正在清除表单。

在我的场景中,除了一个文本区域之外,一切都变得清晰起来。所以对于那个

我使用了以下方法

模型类

public class SomeModel 
{
 ...

 public list<user> userlist {get; set}
}

控制器类

[HttpPost]
public ActionResult SomeAction(SomeModel model) 
{
     model.userlist = new List<user>();

     if (ModelState.IsValid)
     {
        .....

        ModelState.Clear();
        ModelState.Remove(model.SampleTextArea);
        model.SampleTextArea = ""
     }  


    return View("SomeAction", model); 
}

现在一切都第一次正常工作。但没有刷新页面如果我在此表单中填写相同的值并单击提交,

因为它说模型验证无效,所以对于相同的模型值,该函数从第二次尝试开始就无法正常工作。

它的错误是“userlist” System.Int[32] 得到 null

如何在没有页面定向的情况下正确清除此文本区域值(RedirecToAction())

【问题讨论】:

  • SomeModel 的默认构造函数是否实例化了一个新的 List
  • 是的,这适用于第一次尝试,从第二次尝试开始,对于相同的模型属性,这不起作用
  • 你试过设置model.userlist = new List();就在返回之前...当您返回模型时,您的列表对象似乎为空。

标签: c# asp.net-mvc razor


【解决方案1】:

here。我使用此代码从 ModelState 中删除单个条目:

    /// <summary>
    /// Removes the ModelState entry for this property.
    /// </summary>
    public static void RemoveFor<M, P>(this ModelStateDictionary modelState, 
                                       Expression<Func<M, P>> property)
    {
        string key = KeyFor(property);

        modelState.Remove(key);
    }

    /// <summary>
    /// Returns the ModelState key used for this property.
    /// </summary>
    private static string KeyFor<M, P>(Expression<Func<M, P>> property)
    {
        return ExpressionHelper.GetExpressionText(property);
    }

用法:

// Remove value from both ModelState and the model
ModelState.RemoveFor((SomeModel m) => m.SampleTextArea);
model.SampleTextArea = "";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    • 2016-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多