In this article, I will show you how to clear form after submit in asp.net MVC. Before, when I submitting the asp.net mvc form; the page fields are not cleared; the problem on resetting of all form fields. But the page still have the values.
This is due to HTML helpers, It will completely ignore the model class. So that we need to clear the class and return view. After this, It worked perfectly.
Here, I used contact class.
Contact class:
public class Contact
{
[Required]
public string Name { get; set; }
[Required, EmailAddress]
public string Email { get; set; }
[Required]
public string Subject { get; set; }
[Required]
public string Body { get; set; }
}
ContactUsController:
[HttpPost]
public ActionResult Save(Contact contact)
{
//Save data to DB here ...
ModelState.Clear();
Contact ObjContact = new Contact() { Name = string.Empty,
Email = string.Empty,
Subject = string.Empty,
Body = string.Empty };
return View("Index", ObjContact);
}
Index view:
@using (Html.BeginForm("Index", "CustomerService",FormMethod.Post)){
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="name">
Name
</label>
<input type="text" name="Name" class="form-control" id="name" placeholder="Enter name" required="required" />
</div>
<div class="form-group">
<label for="email">
Email Address
</label>
<div class="input-group">
<span class="input-group-addon">
<span class="glyphicon glyphicon-envelope"></span>
</span>
<input type="email" name="Email" class="form-control" id="email" placeholder="Enter email" required="required" />
</div>
</div>
<div class="form-group">
<label for="subject">
Subject
</label>
<select id="subject" name="Subject" class="form-control" required="required">
<option value="na" selected="">Choose One:</option>
<option value="General Customer Service">General Customer Service</option>
<option value="Suggestions">Suggestions</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="name">
Message
</label>
<textarea name="body" id=" body" class="form-control" rows="9" cols="25" required="required"
placeholder="Message"></textarea>
</div>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-primary pull-right" id="btnContactUs">
Send Message
</button>
</div>
</div>
}
Post your comments / questions
Recent Article
- How to create custom 404 error page in Django?
- Requested setting INSTALLED_APPS, but settings are not configured. You must either define..
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
Related Article