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
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
Im trying to call the java script confirmation form submit but it skips it. It directly calls the controller even though i want to run first the java script for confirmation.
I dont know what im doing wrong. Still new to JV Scripts.
HTML
#model WMS_Web.Models.FileMaintenance.PrincipalModels
#section Scripts {
#Scripts.Render("~/Script/FileMaintenance/CommonFunction.js")
}
#{
ViewBag.Title = "PrincipalModel";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Principal</h2>
#using (Html.BeginForm("Create","Principal",FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CompanyId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CompanyId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CompanyId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button onclick='functionConfirm("Do you like Football?", function yes() {
alert("Yes")
},
function no() {
alert("no")
});'>XXX</button>
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back", "ViewPrincipal")
</div>
Java Script
function functionConfirm(msg, myYes, myNo) {
var confirmBox = $("#confirm");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes,.no").unbind().click(function () {
confirmBox.hide();
});
confirmBox.find(".yes").click(myYes);
confirmBox.find(".no").click(myNo);
confirmBox.show();
}
You can try this:
#using (Html.BeginForm("Create","Principal",FormMethod.Post))
{
#Html.AntiForgeryToken()
...
<input type="submit" name="name" value="Save" onclick="javascript: return SubmitForm();" />
}
Javascript:
function SubmitForm() {
var r = confirm("Are you sure you want to submit?");
if (r == false) {
return false;
}
// do something
return true;
}
In my project, I have a main page for the document creation in DocumentsController where the user is able to change the status of the document. If the status is NEW, the user is allowed to add a new device ("part") to the document.
My goal is to insert a string to div#newDevice on ajax form submit. However, the html result is not rendered inside my main view but is rendered as a link ..../PartsBoxes/CreatePartial instead.
How could I fix that issue?
My main page part:
<input type="button" value="Add a new box" id="addNewBoxButton" class="add_new_btn" />
<input type="button" value="Add box from db" id="addDBBoxButton" class="add_existent_btn" />
<hr />
<div id="newDevice"></div>
<hr />
<script>
$("#addNewBoxButton").on("click", function () {
var deviceId = 1;
$.get('#Url.Action("CreatePartial", "PartsBoxes")',{
deviceId: deviceId
},
function (data) {
$("#newDevice").html(data);
});
});
</script>
my partial view:
#model NTStock.Models.BoxPartsViewModel
#{
ViewBag.Title = "Create";
}
#using (Ajax.BeginForm("CreatePartial", new AjaxOptions { UpdateTargetId = "newDevice" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.DocumentId)
<div class="form-group">
#Html.LabelFor(model => model.InternalName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.InternalName, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.InternalName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SerialNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SerialNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SerialNumber, "", new { #class = "text-danger" })
</div>
</div>
//......///
<div class="form-group deviceManipulations">
#Html.LabelFor(model => model.DeinstallationDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DeinstallationDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DeinstallationDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save box" class="btn btn-default" />
</div>
</div>
</div>
}
and the method:
[HttpPost]
[ValidateAntiForgeryToken]
public ContentResult CreatePartial(BoxPartsViewModel partsBox)
{
if (ModelState.IsValid)
{
//do something
}
return Content("string to return");
}
as a result I get:
Firstly you should be sure jquery.unobtrusive-ajax is loaded in your page and you dont use jquery 1.9 version because it doesnt support jquery live methods.
Reference : http://jquery.com/upgrade-guide/1.9/
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
Then I would suggest to use jquery .load() function to load partial view into target element and use JsonResult instead of ActionResult to achieve your goal like following.
// jquery
<script>
$("#addNewBoxButton").on("click", function () {
var deviceId = 1;
$("#newDevice").load('#Url.Action("CreatePartial", "PartsBoxes")' + "/" deviceId );
});
</script>
//controller
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult CreatePartial(BoxPartsViewModel partsBox)
{
if (ModelState.IsValid)
{
//do something
}
return Json(new { data = "string to return" });
}
I try to override a <form> on submit behavior, so I use the next code:
<script type="text/javascript">
$(function () {
var form = $("#FilterForm");
form.submit(function () {
alert("Submit");
$.ajax({
url: form.attr("action"),
type: 'POST',
data: new FormData(this),
processData: false,
contentType: false,
success: function (response) {
alert(response);
$('#Container').html(response);
},
error: function () {
$('#Container').html(loadingFailedStr);
},
timeout: 15000
});
return false;
})
});
</script>
This script block locates after my form. This form declared in the partial view:
<div class="panel card-0">
<div class="panel-body">
#using (Html.BeginForm("TasksGridViewPartial", "Tasks", new { StaffId = staffId, StageId = stageId }, FormMethod.Post, new { id = "FilterForm", enctype = "multipart/form-data" }))
{
<fieldset>
<div class="form-group row">
<div class="col-md-2 col-sm-6">
#Html.Label(Headers.DateCreate)
<div class="datepicker">
#Html.TextBoxFor(m => m.CreatedOn1, new { #class = "form-control" })
</div>
<div class="datepicker">
#Html.TextBoxFor(m => m.CreatedOn2, new { #class = "form-control" })
</div>
</div>
<div class="col-md-2 col-sm-6">
#Html.Label(Headers.DateClose)
<div class="datepicker">
#Html.TextBoxFor(m => m.ClosedOn1, new { #class = "form-control" })
</div>
<div class="datepicker">
#Html.TextBoxFor(m => m.ClosedOn2, new { #class = "form-control" })
</div>
</div>
<div class="col-md-2 col-sm-6">
#Html.Label(Headers.DateStart)
<div class="datepicker">
#Html.TextBoxFor(m => m.StartDate1, new { #class = "form-control" })
</div>
<div class="datepicker">
#Html.TextBoxFor(m => m.StartDate2, new { #class = "form-control" })
</div>
</div>
<div class="col-md-2 col-sm-6">
#Html.Label(Headers.DateEnd)
<div class="datepicker">
#Html.TextBoxFor(m => m.EndDate1, new { #class = "form-control" })
</div>
<div class="datepicker">
#Html.TextBoxFor(m => m.EndDate2, new { #class = "form-control" })
</div>
</div>
<div class="col-md-2 col-sm-6">
#Html.Label(Headers.DateCheck)
<div class="datepicker">
#Html.TextBoxFor(m => m.VerifiedOn1, new { #class = "form-control" })
</div>
<div class="datepicker">
#Html.TextBoxFor(m => m.VerifiedOn2, new { #class = "form-control" })
</div>
</div>
<div class="col-md-2 col-sm-6">
#Html.Label(Headers.TaskNumber)
<div style="padding: 4px;">
#Html.TextBoxFor(m => m.VerifiedOn1, new { #class = "form-control", type = "number" })
</div>
<div style="padding: 4px;">
#Html.TextBoxFor(m => m.VerifiedOn2, new { #class = "form-control", type = "number" })
</div>
</div>
</div>
<div class="form-group row">
<div class="col-md-3 col-sm-6">
#Html.LabelFor(m => m.Executors)
#Html.ListBoxFor(m => m.Executors, executors, new { #class = "selectpicker form-control", #title = Messages.ChooseExecutors, multiple = "" })
</div>
<div class="col-md-3 col-sm-6">
#Html.LabelFor(m => m.Projects)
#Html.ListBoxFor(m => m.Projects, projects, new { #class = "selectpicker form-control", #title = Messages.ChooseProjects, multiple = "" })
</div>
<div class="col-md-3 col-sm-6">
#Html.LabelFor(m => m.Statuses)
#Html.ListBoxFor(m => m.Statuses, statuses, new { #class = "selectpicker form-control", #title = Messages.ChooseStatuses, multiple = "" })
</div>
</div>
<div class="form-group row" style="padding-top: 24px;">
<div class="col-md-12">
<button type="submit" class="btn btn-primary">#Actions.Apply</button>
<button type="button" class="btn btn-default">#Actions.ClearFilters</button>
<button type="button" class="btn btn-default">#Actions.ShowAccepted</button>
<button type="button" class="btn btn-default">#Actions.HideAccepted</button>
</div>
</div>
</fieldset>
}
</div>
</div>
I render this partial view calling #Html.Action("FilterPartial").
The most interesting is that I checked form variable in on document ready event and it was declared as need. But submit still is not called.
Where may a problem be?
return false isn't enough, you also need to block the default:
$(function () {
var form = $("#FilterForm");
form.submit(function (e) { // Pass the event to the function
e.preventDefault(); // Stop the form submitting.
$.ajax({
url: form.attr("action"),
type: 'POST',
data: new FormData(this),
processData: false,
contentType: false,
success: function (response) {
alert(response);
$('#Container').html(response);
},
error: function () {
$('#Container').html(loadingFailedStr);
},
timeout: 15000
});
return false;
})
});
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
.....
});