I have the following view
#using System.Linq;
#model MyCompanyNET.Models.ViewModels.AdministratorViewModel
<style type="text/css">
span {
padding-right: 10px;
}
...
</style>
<div class="manage">
<ul class="nav nav-tabs" id="myTab">
<li class="active">
<a data-toggle="tab" href="#invite">
<span class="glyphicon glyphicon-inbox"></span>Invite
</a>
</li>
...
</ul>
<div class="tab-content">
<div id="invite" class="tab-pane active fade in">
#Html.Partial("_InvitePartial", Model)
</div>
...
</div>
</div>
#section scripts {
<script>
$(function () {
$("input[type=button]").click(function () {
var data_email = $('#email').val();
var data_product = $('#product option:selected').text();
$.ajax({
url: '#Url.Action("SendInvite")',
type: 'POST',
data: { email: data_email, product: data_product },
success: function (result) {
$('#fail_message').html(result.result_failure);
$('#success_message').html(result.result_success);
}
});
});
});
</script>
}
The partial view is
#using (Html.BeginForm("SendInvite", "Tools", FormMethod.Post,
new
{
#class = "form-horizontal",
enctype = "multipart/form-data",
role = "form"
}))
{
#Html.AntiForgeryToken()
<h2>Invite Users</h2>
<div class="form-group">
#Html.LabelFor(m => m.EmailAddress, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.EmailAddress, new { #class = "form-control", id = "email" })
#Html.ValidationMessageFor(m => m.EmailAddress)
</div>
</div>
<div class="form-group">
#Html.Label("Access To", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownList("Product", new SelectList(
new List<Object> {
new { Text = "Product1", Value = "Product1" },
new { Text = "Product2", Value = "Product2" },
new { Text = "All", Value = "All" }},
"Value",
"Text"),
new { #class = "form-control", id = "product" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<span id="fail_message" class="label label-danger"></span>
<span id="success_message" class="label label-success"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" value="Invite User" class="btn btn-primary" />
</div>
</div>
}
and my controller is
[AllowAnonymous]
public async Task<JsonResult> SendInvite(string email, string product)
{
ApplicationUser user = null;
string result = String.Empty;
if (ModelState.IsValid)
{
if (String.IsNullOrEmpty(email))
{
return Json(new
{
result_success = String.Empty,
result_failure = "Please enter and email address"
}, JsonRequestBehavior.AllowGet);
}
}
... // Do stuff with email and product.
}
Now when this partial view code was in the view itself, everything worked fine. I'd get both the entered email address and the selected product coming through to my controller method SendInvite, but now the button does not even fire.
Now, I have changed the
<input type="button" value="Invite User" class="btn btn-primary"/>
to use submit
<input type="submit" value="Invite User" class="btn btn-primary"/>
This now calls my controller method but without the email parameter, which is always null(?). To make things worse, the return Json(new ... also does not render my <span id="success_message" class="label label-success"></span>s and it used to when everything was in the main view. Why is this occurring and how an I fix it?
Thank for your time.
the name of the email field is EmailAddress not email.. change your parameter name to string EmailAddress or you can change your markup to
#Html.TextBoxFor(m => m.EmailAddress, new { #class = "form-control", Name="email", id = "email" })
trick is the make the name of the field and your parameter name match, not the id.
Killercam, regarding your form submitting. Did you change it back to type="button" and not type="submit"? If not, reason is when you click the button, it will submit it and will disregard your JavaScript.
try decorating your action method by HttpPost
Related
I have the following View code in which I am displaying a list of flights.
#using Airline_Reservation_System.Models;
#{
AirlineContext ac = new AirlineContext();
var ddlcabin = ac.Cabins.ToList();
}
<div class="container d-flex flex-column align-items-center py-5">
#{
foreach (var item in Model)
{
<div class="flight mb-2">
<div class="info-label">
<span>Flight Info</span>
</div>
<div class="toFrom">
<h3 id="FCity_#item.FlightID">#item.FromCity </h3>
<span><i class="fa mx-4 fa-plane"></i></span>
<h3 id="TCity_#item.FlightID">#item.ToCity</h3>
</div>
<div class="info d-flex">
<p class="me-2 " id="DDate_#item.FlightID">#item.DepartureDate.ToShortDateString()</p>
<p class="me-2" id="DTime_#item.FlightID">#item.DepartureTime.ToShortTimeString()</p>
<p class="me-2 " id="ATime_#item.FlightID">#item.ArrivalTime.ToShortTimeString()</p>
<select id="CFare_#item.Fare" class="form-control me-2">
#foreach (var re in ddlcabin)
{
<option value="#re.CabinsId">#re.CabinName (#re.Fare)</option>
}
</select>
<button class="form-control btn btn-primary" onclick="Save(#item.FlightID,#item.CabinsId)">select </button>
#*#Html.ActionLink("Select", "ReserveFlight", "Flights", new { #class = "btn SelectFlight btn-primary" })*#
</div>
</div>
}
}
}
<script>
function Save(id, cabinsId) {
var Fid = id;
var cid = cabinsId;
window.location.href = '#Url.Action("signUp","User")';
$.ajax({
method: 'GET',
url:'/Flights/ReserveFlight',
data: { FlightId: Fid, CabinId: cid }
});
}
</script>
Here in the script section, I called the first action method signUp in the User controller and after that, in the Ajax call, I posted data on the URL /Flights/ReserveFlight
but the problem is that In the first call the control goes to the signUp method in the User controller, but before opening its view the control automatically goes to action called by ajax means to this action which is:
public ActionResult ReserveFlight(int FlightId, int CabinId)
{
FlightReservation reserve = new FlightReservation();
reserve.CabinsId = CabinId;
reserve.Id = FlightId;
reserve.PessengerId = Convert.ToInt32(Session["UserId"]);
db.FlightReservations.Add(reserve);
db.SaveChanges();
return View();
}
this action gets executed and on the line:
db.SaveChanges();
it shows an exception because the pessengerId is going null.
when I continue it then the view of the signUp method gets displayed.
here is the view:
#using (Html.BeginForm("signUp", "User", FormMethod.Post,))
{
<div>
<div>
<div>
#Html.EditorFor(model => model.FullName, new { htmlAttributes = new { #class = "form-control", id = "fullName" } })
</div>
</div>
<div>
<div class="col-md-5 offset-md-1">
#Html.DropDownListFor(m => m.Genderid, ViewBag.gender as SelectList, "--select gender--", htmlAttributes: new { #class = "form-control", id = "gender" })
</div>
<div class="col-md-5">
#Html.EditorFor(m => m.DOB, new { htmlAttributes = new { #class = "form-control", type = "date", id = "dob" } })
</div>
</div>
<div class="row mb-3">
<div class="col-md-5 offset-md-1">
#Html.EditorFor(model => model.contact, new { htmlAttributes = new { #class = "form-control", type = "number", id = "contact" } })
</div>
<div class="col-md-5">
#Html.EditorFor(model => model.Cnic, new { htmlAttributes = new { #class = "form-control", id = "cnic" } })
</div>
</div>
<div class="row mb-3">
<div class="col-md-10 offset-md-1">
#Html.DropDownListFor(m => m.CityId, ViewBag.cityList as SelectList, "--select city--", htmlAttributes: new { #class = "form-control", id = "city" })
</div>
</div>
<div class="row mb-3">
<div class="col-md-10 offset-md-1">
#Html.EditorFor(model => model.email, new { htmlAttributes = new { #class = "form-control", id = "email" } })
</div>
</div>
<div class="row mb-3">
<div class="col-md-5 offset-md-1">
#Html.EditorFor(model => model.password, new { htmlAttributes = new { #class = "form-control", id = "password" } })
</div>
<div class="col-md-5">
#Html.EditorFor(model => model.cPassword, new { htmlAttributes = new { #class = "form-control", id = "cpassword" } })
</div>
</div>
<div class="row">
<div class="offset-md-1 col-md-10">
<input type="button" value="Sign Up" class="btn btn-primary" onclick="signUp()" />
</div>
</div>
</div>
}
<script src="~/Scripts/jquery-3.6.0.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script>
function signUp() {
var obj = {
FullName: $('#fullName').val(),
Genderid: $('#gender').val(),
DOB: $('#dob').val(),
Cnic: $('#cnic').val(),
CityId: $('#city').val(),
contact: $('#contact').val(),
email: $('#email').val(),
password: $('#password').val(),
cPassword: $('#cpassword').val()
};
$.ajax({
method: "POST",
url: "/User/signUp",
data: obj,
success: function () {
alert("success");
},
error: function () {
alert("failed");
}
});
}
</script>
when I submit the form, Data gets inserted into the database but In the ajax call section, the error callback function is executed and alert shows
failed
I am creating a feedback form by FormMethod.Post method in mvc. Now, in my form data is saving but after save the data page is refreshed so that user cant know that data is successfully inserted or not. So, for thats why I want to alert the javascript and refresh the current page.
I have done many things but didnt work anything.
So, let I am showing you the last thing I tried that in this code.
Here is my view
<script>
#ViewBag.scripCall
function Callback() {
alert("Callback function is working");
}
</script>
#using (Html.BeginForm("Create", "FeedBack", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="container">
<div class="row">
<div class="col-sm-3">
<img src="~/images/default.png" style="margin:10px" height="200" width="200" id="imagePreview" />
<input type="file" name="ImageUpload" accept="image/jpeg, image/png" id="ImageUpload"
onchange="ShowImagePreview(this, document.getElementById('imagePreview'))" class="control-label" />
</div>
<div class="col-sm-2">
#Html.LabelFor(model => model.FullName, new { #class = "control-label" })
</div>
<div class="col-sm-8">
#Html.TextBoxFor(model => model.FullName, new { #class = "form-control", placeholder = "Enter The Name" })
</div>
<div class="col-sm-9">
<br />
</div>
<div class="col-sm-1">
#Html.LabelFor(model => model.Occupation, new { #class = "control-label" })
</div>
<div class="col-sm-8">
#Html.DropDownList("Occupation", ViewData["occupationList"] as SelectList, new {#class="control-label", style="width:250px;" })
</div>
<div class="col-sm-9">
<br />
</div>
<div class="col-sm-3">
#Html.LabelFor(model => model.UserFeedBack, new { #class = "control-label" })
</div>
<div class="col-sm-8">
#Html.TextBoxFor(model => model.UserFeedBack, new { #class = "form-control", placeholder = "Enter FeedBack", style="height:250px;" })
</div>
<div class="col-sm-3">
<input type="submit" id="btn_save" class="button" value="Save" />
</div>
</div>
<div class="row">
<span class="control-label" style="color:red">Note : Please do not upload <b>DSLR photo</b>. It does not support. Thank You...!!!</span>
</div>
</div>
}
Here is my controller
public ActionResult Create(FeedBackViewModel feedbackViewModel)
{
try
{
HttpPostedFileBase file = Request.Files["ImageUpload"];
if (file != null)
{
string fileName = Path.GetFileNameWithoutExtension(feedbackViewModel.ImageUpload.FileName);
string extension = Path.GetExtension(feedbackViewModel.ImageUpload.FileName);
fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
feedbackViewModel.ImageUpload.SaveAs(Path.Combine(Server.MapPath("~/images/"), fileName));
}
ContentRepository service = new ContentRepository();
int i = service.CreateFeedBack(file, feedbackViewModel);
if (i == 1)
{
ViewBag.scripCall = "Callback();";
return View();
//return Content("<script language='javascript' type='text/javascript'>alert('Thanks for Feedback!');</script>");
}
else
{
return Content("<script language='javascript' type='text/javascript'>alert('Sorry, Something went wrong. Please Try Again...!!!');</script>");
}
}
catch (Exception ex)
{
return View();//"Error", new HandleErrorInfo(ex, "StaffRegistration", "Create"));
}
}
Now, in this code the latest thing I triedto show the alert by #ViewBag.scripCall and also the refresh the current page but it also not working.
Thank You.
I'm having following asp.net mvc 5 web application view page , Prevously its worked very well.
#model project_name.Models.SearchBrochureVM
#{
ViewBag.Title = "Brochure_Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h4>Product Brochure Generation</h4>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group"></div>
<div class="row">
<div class="col-xs-6">
<div class="form-group">
#Html.LabelFor(m => m.Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.Type, Model.TypeList, "Select the type", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Type, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
#Html.LabelFor(m => m.Category, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.Category, Model.CategoryList, "Select the category", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Category, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div>
</div>
<div class="row">
<div class="col-xs-6">
<div class="form-group">
#Html.LabelFor(m => m.Country, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.Country, Model.CountryList, "Select the country", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Country, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
#Html.LabelFor(m => m.Product, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.Product, Model.ProductList, "Select the subsidary", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Product, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button id="search" type="button" class="btn btn-success submit">Select Information</button>
</div>
</div>
</div>
}
<form id="brochureform">
<table class="table">
<thead>
<tr>
<th>Property_ID</th>
<th>IsChecked</th>
<th>Property Tile</th>
</tr>
</thead>
<tbody id="table"></tbody>
</table>
</form>
<table id="template" class="table" style="display: none;">
<tr>
<td>
<span></span>
<input type="hidden" name="[#].Property_ID" />
</td>
<td>
<input type="checkbox" name="[#].IsChecked" value="true"/>
<input type="hidden" name="[#].IsChecked" value="false"/>
</td>
<td>
<span></span>
</td>
</tr>
</table>
<div style="width:50%; float:left;text-align:left"><button id="resetborchure" type="button" class="btn btn-warning submit">Reset Brochure</button> </div>
<div style="width:50%; float:left;text-align:right"><button id="createborchure" type="button" class="btn btn-danger submit">Create Brochure</button> </div>
<script type="text/javascript">
</script>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryui")
<script type="text/javascript">
var type = $('#Type');
var category = $('#Category');
var country = $('#Country');
var product = $('#Product');
$('#search').click(function () {
var url = '#Url.Action("FetchProductProperties")';
$.getJSON(url, { type: type.val(), category: category.val(), country: country.val(), product: product.val() }, function (data) {
$.each(data, function (index, item) {
var clone = $('#template').clone();
clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
var cells = clone.find('td');
cells.eq(0).children('span').text(item.ID);
cells.eq(0).children('input').val(item.ID);
cells.eq(1).children('input').first().prop('checked', item.CheckOrNot)
cells.eq(2).children('span').text(item.Name);
$('#table').append(clone.find('tr'));
});
});
});
$('#createborchure').click(function () {
var data = $('#brochureform').serialize();
var url = '#Url.Action("Create_Brochure", "Brochure")';
//$.get(url, data, function (result) {
// window.location = url;
//});
$.ajax({
url: url,
type: 'GET',
data: data
})
.success(function (response) {
});
});
$('#resetborchure').click(function () {
table.empty();
});
</script>
}
Above view have two buttons called Reset Brochure and Create Brochure
Once I click Reset Brochure button its clear the table in that view and once I select Create Brochure its redirect to another view.
previously these two functions worked very well , but I cannot understand this isn't give any response once I click these buttons.
Since your wanting to redirect to another method (passing the values of the form controls in the table) there is no reason to use ajax, and instead you should just do a normal submit.
Replace the <form id="brochureform"> element with
#using (Html.BeginForm("Create_Brochure", "Brochure", FormMethod.Get))
{
<table class="table">
<thead>
....
</thead>
<tbody id="table"></tbody>
</table>
<input type="submit" value="CreateBrochure" />
}
and remove the <button id="createborchure" ...>Create Brochure</button> element and its associated script. This will now make a GET call to your public ActionResult Create_Brochure(IEnumerable<ProductsPropertiesVM> model) method
However this will also create a really ugly url and there is a risk that you will exceed the query string limit and throw an exception. In general GET methods should never have parameters which are collections.
From the DotNetFiddle you provided in chat, its unclear how your using the data you pass to the method (your create a variable string ids but then never actually use it. Assuming you do actually need it for the view you return in that method, I would suggest adding another POST method to avoid the issues above.
[HttpPost]
public ActionResult Initialize_Brochure(IEnumerable<ProductsPropertiesVM> model)
{
IEnumerable<int> selectedIDs = model.Where(x => x.IsChecked).Select(x => x.Property_ID);
string ids = string.Join(",", selectedIDs);
return RedirectToAction("Create_Brochure", new { id = ids });
}
and change the Create_Brochure() method to
public ActionResult Create_Brochure(string id)
{
....
}
and finally modify the BeginForm() to
#using (Html.BeginForm("Initialize_Brochure", "Brochure", FormMethod.Post))
This means you url will simply be something like
/Brochure/Initialize_Brochure/2,4,5 depending on the checkboxes you select
i want to set the DDL selected item with item inserted in popup page.
Used script sample from here - http://www.advancesharp.com/blog/1126/search-sort-paging-insert-update-and-delete-with-asp-net-mvc-and-bootstrap-modal-popup-part-2
in JsonResult i see the inserted value (checking in Debug mode with breakpoint), but need help with setting this value as selected in DDL in main page.
public ActionResult WorkPlaces(int id = 0)
{
var workPlace = new Work();
return PartialView("WorkPlaces", workPlace);
}
[HttpPost]
public JsonResult WorkPlaces(Work work)
{
if (ModelState.IsValid)
{
db.Works.Add(work);
db.SaveChanges();
return Json(new { success = true });
}
return Json(work, JsonRequestBehavior.AllowGet);
}
Model classes
public class Person
{
public int Id { get; set; }
[Display(Name = "Person Name")]
[Required(AllowEmptyStrings = false, ErrorMessage = "Name is required")]
public string Name { get; set; }
public Nullable<int> WorkId { get; set; }
public virtual Work Work { get; set; }
}
public class Work
{
public int Id { get; set; }
[Display(Name = "Work place")]
[Required(AllowEmptyStrings = false, ErrorMessage = "Name is required")]
public string workPlace { get; set; }
}
Main page
#model testAppAuth.Models.Person
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Person</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.WorkId, "WorkId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("WorkId", null, htmlAttributes: new {#class = "form-control"})
#Html.ValidationMessageFor(model => model.WorkId, "", new {#class = "text-danger"})
<a class="btn btn-success" data-modal="" href="/Person/WorkPlaces" id="btnCreate">
<span class="glyphicon glyphicon-plus"></span>
</a>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<!-- modal placeholder-->
<div id='myModal' class='modal fade in'>
<div class="modal-dialog">
<div class="modal-content">
<div id='myModalContent'></div>
</div>
</div>
</div>
#section scripts{
#Scripts.Render("~/Scripts/Appjs/WorkPlace.js")
}
popup page
#model testAppAuth.Models.Work
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 class="modal-title">Add new workplace</h3>
</div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Work place</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.workPlace, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.workPlace, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.workPlace, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="modal-footer">
<span id="progress" class="text-center" style="display: none;">
<img src="/images/wait.gif" alt="wiat" />
Wait..
</span>
<input class="btn btn-primary" type="submit" value="Save" />
<button class="btn btn-warning" data-dismiss="modal">Close</button>
</div>
}
<script>
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
</script>
script for popup
$(function () {
$.ajaxSetup({ cache: false });
$("a[data-modal]").on("click", function (e) {
$('#myModalContent').load(this.href, function () {
$('#myModal').modal({
keyboard: true
}, 'show');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
$('#progress').show();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$('#myModal').modal('hide');
$('#progress').hide();
location.reload();
} else {
$('#progress').hide();
$('#myModalContent').html(result);
bindForm();
}
}
});
return false;
});
}
Also, with this script even i set [Required] attribute in Model classes, it closes if i click close button without filling fields. How to make it not to close?
Your first question:
You can do this using Jquery:
When you are closing the dialog(Sucess) make a Jquery call to a function that will take the submitted value and change the selected item in your main page.
ex:
success: function (result) {
//change the selected item
}
Your second question:
The Ajax Call doesn't care about the Model Validation.
When you are submitting the data from your modal, validate the values of the required fields before making the AJAX Call.
ex.
$('form', dialog).submit(function () {
if(isValidInput()){
$('#progress').show();
//make Ajax Call
}
});
function IsValidInput(){
//do validation
}
For your Question how to validate before closing the Model use the below code
$(function () {
$('#myModal').on('hide.bs.modal', function (event) {
var form = $("#formid");
form.Validate();
if(form.Valid()){
//Ajax;
}
else{
event.PreventDefault();
}})});
Now in ajax Success used jquery to add value to DropDown
I'm working on a form in my application, which I want to post using ajax. The posting works fine and my controller receives the data, but I'd like to just post a success message back to my view instead of refreshing the entire page. Do I have to return a partial view with the information for this, or can I just return a message from my controller? I can't seem to figure out how to do this properly.
<div class="panel panel-gray">
<div class="panel-body">
<form method="POST" action="#Url.Action("SaveWellDetails", "WellManagement")" id="wellform" class="form-horizontal">
<div class="form-group">
#Html.LabelFor(m => m.Id, new { #class = "col-md-3 control-label"})
<div class="col-md-9">
#Html.TextBoxFor(m => m.Id, new { #class = "form-control", disabled = "disabled", id = "WellId", name = "WellId" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Name, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
#Html.TextBoxFor(m => m.Name, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Location, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
#Html.TextBoxFor(m => m.Location, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.WellNumber, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
#Html.TextBoxFor(m => m.WellNumber, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.WellType, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
#Html.TextBoxFor(m => m.WellType, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.SpudDate, new { #class = "col-md-3 control-label" })
<div class="col-md-9">
#Html.TextBoxFor(m => m.SpudDate, new { #class = "form-control" })
</div>
</div>
<div class="panel-footer">
<input type="submit" id="submit" class="btn btn-primary" value="Save Changes" />
<div class="pull-right" id="wellsavesection">
<div id="processing_small" hidden="hidden">
<img src="~/Content/Kendo/Flat/loading_2x.gif" />
</div>
</div>
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#wellform').submit(function () {
console.log("wellId = " + $("#WellId").val());
$("#processing_small").show().hide().fadeIn('slow');
$.ajax({
url: '#Url.Action("SaveWellDetails", "WellManagement")',
type: "POST",
dataType: "json",
data: {
wellId: $('#WellId').val(),
name: $('#Name').val(),
location: $('#Location').val(),
wellNumber: $('#WellNumber').val(),
wellType: $('#WellType').val(),
spudDate: $('#SpudDate').val()
},
error: function (msg) {
$('#wellsavesection').hide().html('<div class="alert alert-danger"><strong>Ouch!</strong> ' + msg.statusText + '</div>').fadeIn('slow');
},
success: function (msg) {
$('#wellsavesection').hide().html('<div class="alert alert-success"><strong>Success!</strong> Form Saved.</div>').fadeIn('slow').delay(1500).fadeOut();
}
});
});
});
</script>
Here's my controller:
[HttpPost]
public ActionResult SaveWellDetails(string wellId, string name, string location, string wellNumber, string wellType, DateTime spudDate)
{
try
{
var wellConctract = new WellContract
{
Id = Convert.ToInt32(wellId),
Name = name,
Location = location,
WellNumber = wellNumber,
WellType = wellType,
SpudDate = spudDate
};
WellService.UpdateWell(wellConctract);
}
catch (Exception e)
{
Log.Error(e);
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Message);
}
return Json(new {success = true}, JsonRequestBehavior.AllowGet);
}
Simply add return false; the end of the $('#wellform').submit(function () {... (after the ajax function, not inside it) and it should work, I tried it out in jsfiddle.
What this does it prevent the form from submitting.
you doesn't need a partial view to do that, your page will refresh each submit because it doing the usual event, try add event.preventDefault() http://api.jquery.com/event.preventdefault/
$('#wellform').submit(function (ev) {
ev.preventDefault();
// put your code below here
.....
});