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 fix HAXM is not installed |in Android Studio
- How to fix CMOS Checksum Error in Computer or Laptop | SOLVED
- Reactivating windows after a Hardware change on PC or Laptop
- FIXED: Windows reported that the hardware of your device has changed. Error code :0xc004F211
- "redirect" is not defined pylance("reportUndefinedVariable)
- This action cannot be completed because the file is open in SQL Server(SQLEXPRESS) - FIXED
- Unicode error 'unicodeescape' codec can't decode bytes in position 2-3: truncated UXXXXXXXX escape
- Could not find the 'angular-devkit/build-angular:dev-server' builder's node package | Angular Error
Related Article