0

I have a form. in that form I have a text area property.once I click submit button I want to show some view bag values in same page, while I'm clearing the form.

In my scenario everything getting clear except one text area. so for that

I have used following approach

Model Class

public class SomeModel 
{
 ...

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

Controller Class

[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); 
}

now everything working fine for the first time. but without page refreshing If I fill same values to this form and click submit,

since its saying model validation invalid this is function not working from 2nd attempt onward for same model values.

its saying error as "userlist" System.Int[32] getting null

how can I clear this text area value properly,without page directing(RedirecToAction())

kez
  • 2,273
  • 9
  • 64
  • 123
  • Does the default constructor for SomeModel instantiate a new List ? – BillRuhl Feb 20 '17 at 16:32
  • yes this is working for 1st attempt and from 2nd attempt onward and for same model properties this is not working – kez Feb 20 '17 at 16:46
  • Have you tried setting model.userlist = new List(); just before the return...it looks like your list object is null when you return the model. – BillRuhl Feb 20 '17 at 16:49

1 Answers1

0

See here. I use this code to remove an individual entry from 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);
    }

Usage:

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