I am trying to send form data to a mvc controller and when the user click the submit form they are asked for input in a prompt box. The these answers need to be submitted with the form to the controller. When submitted at the moment, the JSON data is not being sent to the controller.
Form:
#using (Html.BeginForm("BottomRowData", "Tanks", FormMethod.Post, new { #id = "formBottom"}))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(p => p.TankSerNo)
#Html.HiddenFor(p => p.AnnularPlateRingWidth)
#Html.HiddenFor(p => p.connectedtank)
#Html.HiddenFor(p => p.NumberofAnnularPlates)
#Html.HiddenFor(p => p.LengthofEachAnnularPlate)
<div class="row">
<div class="col-md-1 col-xs-4">
<div class="form-group">
<button type="submit" name="action:Save" class="btn btn-primary">
<span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span> Save
</button>
</div>
</div>
<div class="col-md-4 col-xs-8">
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(p => p.TankOwner, "Tank Owner", htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.DropDownList("TankOwner", null, new { #class = "form-control" })
</div>
</div>
</div>
</div>
<div class="col-md-4 col-xs-6">
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(model => model.connectedtank.SiteID, "Site (Tank Location)", htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.HiddenFor(m => m.connectedtank.SiteID)
#Html.EditorFor(model => model.connectedtank.Site.SiteName, new { htmlAttributes = new { #class = "form-control", #readonly = true } })
</div>
</div>
</div>
</div>
<div class="col-md-3 col-xs-6">
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(model => model.TankNumber, "Tank Number", htmlAttributes: new { #class = "control-label col-md-5" })
<div class="col-md-7">
#Html.EditorFor(m => m.TankNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TankNumber, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
</div>
<hr style="margin-top:0px" />
<fieldset class="fi-border">
<legend class="fi-border">Bottom Row Data</legend>
<div class="row">
<div class="col-sm-3 com-xs-12">
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(model => model.NumberofRowsBottom, "Number of Bottom Rows:", htmlAttributes: new { #class = "control-label col-md-6", #style = "padding-top:0px" })
<div class="col-md-6">
#Html.EditorFor(model => model.NumberofRowsBottom, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NumberofRowsBottom, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="col-sm-6 com-xs-12">
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(model => model.WeldRowSpacing, "Weld Row Spacing or Plate Width (Comma Seperated):", htmlAttributes: new { #class = "control-label col-md-5", #style = "padding-top:0px" })
<div class="col-md-7">
#Html.EditorFor(model => model.WeldRowSpacing, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.WeldRowSpacing, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-3">
<button class="btn btn-default btn-block" type="submit" onclick="JavascriptFunction1()" id="BottomButton">
<strong>1.</strong> Calculate Bottom Row Data
</button>
</div>
<div class="col-sm-12">
#Html.CollectionEditorFor(model => model.BottomRows, "BottomLayout/_AddRow", "/Tanks/GetRowEditor",
"Add Rows", new { #style = "display:none" })
</div>
</div>
}
Script:
<script type="text/javascript" language="javascript">
function JavascriptFunction1() {
var url = '#Url.Action("BottomRowData", "Tanks")';
var NumberofRows = parseFloat($('#NumberofRowsBottom').val());
var numberofPlates = [];
$("#divLoading").show();
var i = 1;
while (i <= NumberofRows) {
numberofPlates.push(prompt("Please enter the number of plates on row " + i));
i++;
}
$.ajax({
type: "POST",
url: url,
traditional: true,
datatype: "json",
data: JSON.stringify(numberofPlates),
success: function(data){
$("#PID")[0].innerHTML = data;
$("#divLoading").hide();
}
});
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> BottomRowData(BottomLayoutViewModel data, string[] postdata)
{
var tank = db.Tanks.Find(data.TankSerNo);
tank.NumberofRowsBottom = data.NumberofRowsBottom;
string[] cRowData = new string[1000];
string BottomWeldData = (tank.Diameter / data.NumberofRowsBottom).ToString();
for (var i = 1; i <= data.NumberofRowsBottom; i++)
{
if(i == 1)
{
cRowData[i] = BottomWeldData;
}
else
{
cRowData[i] = cRowData[1];
BottomWeldData = BottomWeldData + ", " + cRowData[i];
}
}
tank.WeldRowSpacing = BottomWeldData;
db.Entry(tank).State = EntityState.Modified;
await db.SaveChangesAsync();
var Radius = float.Parse((tank.Diameter / 2).ToString());
float sumRowData = 0;
double[] rowLength = new double[1000];
for (var counter = 1; counter <= data.NumberofRowsBottom; counter++)
{
var row = new TankBottomLayout();
if (data.BottomRows != null)
{
row = data.BottomRows.ElementAt(counter - 1);
}
sumRowData += float.Parse(cRowData[counter]);
row.TankSerNo = tank.TankSerNo;
row.Tank = tank;
row.BLORowNumber = counter;
row.BLONumberofPlatesRow = int.Parse(postdata.ElementAt(counter - 1));
rowLength[counter] = 2 * Math.Pow((Math.Pow(Radius, 2) - Math.Pow((sumRowData - Radius), 2)), 0.5);
if(counter == 1)
{
row.BLOWeldRowLength = rowLength[counter];
}
else if(counter < data.NumberofRowsBottom / 2 + 1)
{
row.BLOWeldRowLength = rowLength[counter - 1];
}
else if(counter == data.NumberofRowsBottom)
{
row.BLOWeldRowLength = rowLength[counter - 1];
}
else
{
row.BLOWeldRowLength = rowLength[counter];
}
if(row.ID <= 0)
{
db.TankBottomLayouts.Add(row);
}
else
{
db.Entry(row).State = EntityState.Modified;
}
}
await db.SaveChangesAsync();
return RedirectToAction("BottomLayout", new { TankSerNo = data.TankSerNo });
}
My main problem is that I need a way to ask the user for the number of plates on each row and send that data to the controller in order to calculate the weld spacing on each row. Thanks.
This behaviour is due to Asynchronosity of the Ajax function, Read this post on getting values from Asynchronous functions
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 have a form, where throught templates the html is replaced when the user clicks a button and fills in parts of the form (I do it this way to guide the user in what he fills in first). the problem is at the end I do an ajax call to save all changes to the database, but instead of going to the succes function of the ajax call it goes to the httppost of my controller action and crashes the application.
here's my html code with the templates:
<h2>Nieuwe testrit</h2>
<p>
<input type="button" class="btn btn-primary" value="Terug naar lijst"
onclick="location.href='#Url.Action("index", "TestDrive")'" />
</p>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group" id="stepReloadDiv">
#Html.Label("Auto", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="form-inline">
<input type="text" class="form-control" id="selectCarVIN" value="Selecteer een auto." readonly="readonly" />
<input type="button" class="btn btn-primary btn-outline" value="Auto selecteren" onclick="SelectCar()" />
</div>
<br />
<button class="btn btn-success" onclick="numberOfDays()" ; id="buttonNumberOfDays" disabled>Next <i class="fas fa-arrow-right"></i></button>
#Html.Hidden("carId")
#Html.ValidationMessageFor(model => model.carId, "", new { #class = "text-danger" })
</div>
</div>
</div>
}
#section Scripts {
<script src="~/Scripts/CustomTestDriveAddScript.js"></script>
<script>
function SelectCar() {
var w = $(window).width() - 700;
var h = $(window).height() - 100;
$('#cboxLoadingGraphic').show();
$.colorbox({
href: '#Url.Action("selectcarfortestdrive","car")',
iframe: true,
fastIframe: false,
transition: 'elastic',
innerWidth: w,
innerHeight: h,
scrolling: true
});
}
function SelectCustomer() {
var w = $(window).width() - 100;
var h = $(window).height() - 100;
$('#cboxLoadingGraphic').show();
$.colorbox({
href: '#Url.Action("SelectCustomerForTestDrive","customer")',
iframe: true,
fastIframe: false,
transition: 'elastic',
innerWidth: w,
innerHeight: h,
scrolling: true
});
}
</script>
<script id="lengthQuestionTemplate" type="text/template">
<div class="col-md-10 col-md-offset-2">
<h4>Gaat deze testrit over meer dan 1 uur/meerdere dagen?</h4>
<div class="form-inline">
<button class="btn btn-success btn-outline" onclick='nextStepStartDateMultipleDays();'>Ja <i class="fas fa-check-circle" style="color:green"></i></button>
<button class="btn btn-danger btn-outline" onclick='nextStepStartDateOneDay();'>Nee <i class="fas fa-times-circle" style="color:#af1515"></i></button>
</div>
</div>
</script>
<script id="endDateTemplate" type="text/template">
<div class="col-md-10">
<div class="form-group">
#Html.Label("Einddatum", htmlAttributes: new { #class = "control-label col-md-2" })
#Html.TextBoxFor(model => model.endDate, "{0:yyyy-MM-dd}", new { #class = "form-control", #id = "endDate", #type = "date", #onchange = "endDateChanged();" })
#Html.ValidationMessageFor(model => model.endDate, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.Label("Eindtijd", htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(model => model.endBlockId, new SelectList("", "id", "endTime"), new { #class = "form-control", #id = "endTimeDropdown", #onchange = "endTimeChanged();" })
#Html.ValidationMessageFor(model => model.endBlockId, "", new { #class = "text-danger" })
</div>
<div class="form-group">
<span id="errorMsg"></span>
<button class="btn btn-success col-md-offset-2" onclick="nextStepChooseEndDate('endDate', 'endTimeDropdown')" ; id="buttonChooseEndDate" disabled>Next <i class="fas fa-arrow-right"></i></button>
</div>
</div>
</script>
<script id="startDateTemplate" type="text/template">
#Html.Label("Startdatum", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="form-inline">
#Html.TextBoxFor(model => model.startDate, new { #class = "form-control", #onchange = "startDateChangedSingle();", #type = "date" })
#Html.ValidationMessageFor(model => model.startDate, "", new { #class = "text-danger" })
</div>
<br />
<span id="errorMsg"></span>
<button class="btn btn-success" onclick="nextStepChooseStartDate('startDate');" ; id="buttonTimeSingle" disabled>Next <i class="fas fa-arrow-right"></i></button>
</div>
</script>
<script id="startDateTemplateMultipe" type="text/template">
<div class="col-md-10">
<div class="form-group">
#Html.Label("Startdatum", htmlAttributes: new { #class = "control-label col-md-2" })
#Html.TextBoxFor(model => model.startDate, "{0:yyyy-MM-dd}", new { #class = "form-control", #type = "date", #id = "startDate", #onchange = "startDateChangedMultiple();" })
#Html.ValidationMessageFor(model => model.startDate, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.Label("Starttijd", htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(model => model.startBlockId, new SelectList("", "id", "startTime"), new { #class = "form-control", #id = "startTimeDropdown" })
#Html.ValidationMessageFor(model => model.startBlockId, "", new { #class = "text-danger" })
</div>
<div class="form-group">
<span id="errorMsg"></span>
<button class="btn btn-success col-md-offset-2" onclick="nextStepChooseStartDateMultiple('startDate', 'startTimeDropdown');" ; id="buttonStartMultiple" disabled>Next <i class="fas fa-arrow-right"></i></button>
</div>
</div>
<script id="choseTimeSingle" type="text/template">
#Html.Label("Starttijd", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="form-inline">
#Html.DropDownListFor(model => model.startBlockId, new SelectList("", "id", "time"), new { #class = "form-control", #id = "timeDropdown", #onchange = "startTimeChangedSingle();" })
#Html.ValidationMessageFor(model => model.startBlockId, "", new { #class = "text-danger" })
</div>
<br />
<span id="errorMsg"></span>
<button class="btn btn-success" onclick="nextStepChooseTime('timeDropdown');" ; id="buttonTimeSingle">Next <i class="fas fa-arrow-right"></i></button>
</div>
</script>
<script id="choseLicenceplate" type="text/template">
#Html.Label("Nummerplaat", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="form-inline">
#Html.DropDownListFor(model => model.licenceplateId, new SelectList("", "id", "licenceplate1"), new { #class = "form-control", #id = "licensePlateDropdown" })
#Html.ValidationMessageFor(model => model.licenceplateId, "", new { #class = "text-danger" })
</div>
<br />
<button class="btn btn-success" onclick="nextStepChooseLicenceplate('licensePlateDropdown');" ; id="buttonTimeSingle">Next <i class="fas fa-arrow-right"></i></button>
</div>
</script>
<script id="choseCustomer" type="text/template">
#Html.Label("Klant", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="form-inline">
<input type="text" class="form-control" id="selectCustomerId" value="Selecteer een klant." readonly="readonly" />
#Html.Hidden("customerId")
<input type="button" class="btn btn-primary btn-outline" value="Klant selecteren" onclick="SelectCustomer()" />
</div>
<br />
<button class="btn btn-success" id="buttonSelectCustomer" onclick="nextStepChooseCustomer('customerId');" disabled>Next <i class="fas fa-arrow-right"></i></button>
</div>
</script>
<script id="choseType" type="text/template">
#Html.Label("Type uitlening", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="form-inline">
#Html.DropDownListFor(model => model.customerId, new SelectList(ViewBag.testdriveTypes, "id", "name"), new { #class = "form-control", #id = "testDriveTypeDropDown" })
#Html.ValidationMessageFor(model => model.testDriveTypeId, "",
new { #class = "text-danger" })
</div>
<br/>
<button class="btn btn-success"
onclick="nextStepFinishEdit('testDriveTypeDropDown');">Aanmaken</button>
</div>
</script>
<script id="Done" type="text/template">
<div class="col-md-10 col-md-offset-2">
<h4>Uw testrit is succesvol toegevoegd.</h4>
<br />
<input type="submit" value="Naar testrit" class="btn btn-default" />
</div>
</script>
}
with my ajac call being:
function nextStepFinishEdit(valueId) {
var value = document.getElementById(valueId).value;
testDriveTypeId = value;
$.ajax({
type: "GET",
url: "/NewTestDrives/fundallocation",
data: {
"licenseplateId": licencePlateId,
"carId": carId,
"startDate": startDate,
"endDate": endDate,
"customerId": customerId,
"testDriveTypeId": testDriveTypeId,
"startBlockId": startBlockId,
"endBlockId": endBlockId
},
async: false,
success: function (data) {
var inner = document.getElementById('stepReloadDiv');
inner.innerHTML = document.getElementById('Done').innerHTML;
}
});
}
the code where the call is going to:
public async Task FundAllocation(int licenseplateId, int carId, string startDate, string endDate, int customerId, int testDriveTypeId, int startBlockId, int endBlockId)
{
NewTestDriveModel testDriveModel = new NewTestDriveModel
{
carId = carId,
customerId = customerId,
endBlockId = endBlockId,
endDate = endDate,
licenseplateId = licenseplateId,
startBlockId = startBlockId,
startDate = startDate,
testDriveTypeId = testDriveTypeId
};
var testDrives = testDriveService.GetTestDrivesByDay(Convert.ToDateTime(testDriveModel.startDate));
var customer = customerService.GetCustomerById(testDriveModel.customerId);
var usedLicensplates = new List<int>();
foreach (var drive in testDrives)
{
if (drive.startBlockId == testDriveModel.startBlockId)
{
usedLicensplates.Add(drive.licenceplateId);
}
if (drive.carId == testDriveModel.carId && drive.startBlockId == testDriveModel.startBlockId)
{
return;
}
}
TestDrive testDrive = new TestDrive
{
carId = testDriveModel.carId,
customerId = testDriveModel.customerId,
endBlockId = testDriveModel.endBlockId,
endDate = Convert.ToDateTime(testDriveModel.endDate),
licenceplateId = testDriveModel.licenseplateId,
startBlockId = testDriveModel.startBlockId,
startDate = Convert.ToDateTime(testDriveModel.startDate),
testDriveTypeId = testDriveModel.testDriveTypeId
};
testDriveId = testDriveService.AddTestDrive(testDrive);
Session["testDriveId"] = testDriveId;
CalendarHelper calendarHelper = new CalendarHelper();
CarService carService = new CarService();
string licenceplate = licenseplateService.GetLicenceplateById(testDriveModel.licenseplateId).licenceplate1;
Car car = carService.GetCarById(testDriveModel.carId);
CarModel newCarModel = new CarModel
{
Series = car.series,
Name = car.name,
VINNumber = car.VINNumber,
};
CalendarEventModel model = new CalendarEventModel()
{
CustomerFirstname = customer.firstname,
CustomerLastname = customer.name,
TestDrive = testDriveModel,
Car = newCarModel,
Licenceplate = licenceplate,
TestDriveId = testDriveId
};
MailHelper mailHelper = new MailHelper();
TimeBlock startBlock = timeBlockService.GetTimeBlockById(testDriveModel.startBlockId);
TimeBlock endBlock = timeBlockService.GetTimeBlockById(testDriveModel.endBlockId);
CustomerReservationConfirmationMailModel mailModel = new CustomerReservationConfirmationMailModel()
{
CarSerie = car.series,
CarName = car.name,
Motor = car.motor,
Model = car.modelType,
StartDate = Convert.ToDateTime(testDriveModel.startDate).ToString("dd/MM/yyyy"),
EndDate = Convert.ToDateTime(testDriveModel.endDate).ToString("dd/MM/yyyy"),
StartHour = startBlock.startTime,
EndHour = endBlock.endTime,
Customer = customer,
Licenceplate = licenceplate
};
await mailHelper.SendCustomerReservationConfirmationMail(mailModel);
await calendarHelper.AddEventAsync(model);
}
And my controller actions:
public ActionResult Add()
{
ViewBag.Customer = customerService.All();
ViewBag.testdriveTypes = testDriveTypeService.GetAll();
return View();
}
[HttpPost]
public ActionResult Add(string s)
{
var testDriveId = Session["testDriveId"];
return RedirectToAction("details", new { id = testDriveId });
}
so the ajax call fires, and the database is being update but the succes function where i replace the html is never called, instead it directly goes to my Http post, how can I prevent this.
By default your button that calls the nextStepFinishEdit function will have a type of 'submit'. Since you have this inside of your #html.BeginForm() it will submit that form. This is what is causing your POST request to fire. Just add type='button' like:
<button class="btn btn-success" type='button'
onclick="nextStepFinishEdit('testDriveTypeDropDown');">Aanmaken</button>
MVC5 asp.net After validation the dialog form is break down
1. _Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - Moving Pro Services</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
#if (HttpContext.Current.User.Identity.IsAuthenticated)
{
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
#Html.ActionLink("Moving Pro Services", "Index", "Home", new {area = ""}, new {#class = "navbar-brand"})
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="dropdown">
Services <span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li>#Html.ActionLink("Companies", "Index", "Companies")</li>
<li>#Html.ActionLink("App Versions", "Index", "AppVersions")</li>
#if (User.Identity.IsAuthenticated)
{
if (User.IsInRole("Administrator"))
{
<li>#Html.ActionLink("Create User", "Register", "Account")</li>
}
}
</ul>
</li>
<li>#Html.ActionLink("About", "About", "Home")</li>
<li>#Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
#Html.Partial("_LoginPartial")
</div>
</div>
}
</div>
<div class="container body-content">
#RenderBody()
<hr/>
<footer>
<p>© #DateTime.Now.Year - Moving Pro Services</p>
</footer>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
<div id='myModal' class='modal fade in'>
<div class="modal-dialog">
<div class="modal-content">
<div id='myModalContent'></div>
</div>
</div>
</div>
</body>
</html>
2. Model
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Maintenance.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Company
{
public int ID { get; set; }
[Display(Name = "Company Name")]
[StringLength(100)]
public string CompanyName { get; set; }
[Display(Name = "Server Alias")]
[StringLength(100)]
public string ServerAlias { get; set; }
[Display(Name = "Server Name")]
public string ServerName { get; set; }
[Display(Name = "Database Name")]
public string DatabaseName { get; set; }
[Display(Name = "Email Database Name")]
public string EmailDatabaseName { get; set; }
[Display(Name = "Integrated Security")]
public bool IntegratedSecurity { get; set; }
[Display(Name = "User Name")]
public string UserName { get; set; }
[Display(Name = "PWD")]
public string Password { get; set; }
[Display(Name = "App Key")]
public string AppKey { get; set; }
[StringLength(20)]
[Display(Name = "App Version")]
public string AppVersion { get; set; }
[Display(Name = "In Home Estimate")]
public bool InHomeEstimate { get; set; }
[Display(Name = "Foreman Inventory")]
public bool ForemanInventory { get; set; }
[Display(Name = "Docs")]
public bool Documents { get; set; }
[Display(Name = "Storage Scan In")]
public bool StorageScanIn { get; set; }
[Display(Name = "Storage Scan Out")]
public bool StorageScanOut { get; set; }
[Display(Name = "Scan At Delivery")]
public bool ScanAtDelivery { get; set; }
[Display(Name = "Amazon Rds")]
public bool AmazonRds { get; set; }
[Display(Name = "Amazon Region")]
[StringLength(20)]
public string AmazonRegion { get; set; }
[Display(Name = "Amazon Identifier")]
public string AmazonIdentifier { get; set; }
[Display(Name = "App Version")]
public virtual AppVersion AppVersion1 { get; set; }
}
}
3. Controller
// GET: Companies/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Company company = _db.Companies.Find(id);
if (company == null)
{
return HttpNotFound();
}
ViewBag.AppVersion = new SelectList(_db.AppVersions, "AppVersion1", "AppVersionDescription", company.AppVersion);
return PartialView(company);
}
// POST: Companies/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,CompanyName,ServerAlias,ServerName,DatabaseName,EmailDatabaseName,IntegratedSecurity,AppKey,AppVersion,InHomeEstimate,ForemanInventory,Documents,StorageScanIn,StorageScanOut,ScanAtDelivery,AmazonRds,AmazonRegion,AmazonIdentifier")] Company company)
{
if (ModelState.IsValid)
{
_db.Entry(company).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.AppVersion = new SelectList(_db.AppVersions, "AppVersion1", "AppVersionDescription", company.AppVersion);
return PartialView(company);
}
4. View
#model Maintenance.Models.Company
#using (Html.BeginForm())
{
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Edit Company</h4>
</div>
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ID)
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group margin-small">
#Html.LabelFor(model => model.CompanyName, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.CompanyName, new { htmlAttributes = new { #class = "form-control", autofocus = "" } } )
#Html.ValidationMessageFor(model => model.CompanyName, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
<div class="form-group margin-small">
#Html.LabelFor(model => model.ServerAlias, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.ServerAlias, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ServerAlias, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
<div class="form-group margin-small">
#Html.LabelFor(model => model.ServerName, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.ServerName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ServerName, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
<div class="form-group margin-small">
#Html.LabelFor(model => model.DatabaseName, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.DatabaseName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DatabaseName, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
<div class="form-group margin-small">
#Html.LabelFor(model => model.EmailDatabaseName, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.EmailDatabaseName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EmailDatabaseName, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
<div class="form-group margin-small">
<div class="col-md-5">
<div class="checkbox control-checkbox">
#Html.EditorFor(model => model.IntegratedSecurity, new { htmlAttributes = new { #class = "input-control-checkbox" } })
#Html.ValidationMessageFor(model => model.IntegratedSecurity, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
#Html.LabelFor(model => model.IntegratedSecurity, htmlAttributes: new { #class = "control-label col-md-7 control-label-checkbox" })
</div>
<div class="form-group margin-small">
#Html.LabelFor(model => model.AppKey, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.AppKey, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AppKey, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
<div class="form-group margin-small">
#Html.LabelFor(model => model.AppVersion, "App Version", htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.DropDownList("AppVersion", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.AppVersion, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
<div class="form-group margin-small">
<div class="col-md-5">
<div class="checkbox control-checkbox">
#Html.EditorFor(model => model.InHomeEstimate, new { htmlAttributes = new { #class = "input-control-checkbox" } })
#Html.ValidationMessageFor(model => model.InHomeEstimate, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
#Html.LabelFor(model => model.InHomeEstimate, htmlAttributes: new { #class = "control-label col-md-7 control-label-checkbox" })
</div>
<div class="form-group margin-small">
<div class="col-md-5">
<div class="checkbox control-checkbox">
#Html.EditorFor(model => model.ForemanInventory, new { htmlAttributes = new { #class = "input-control-checkbox" } })
#Html.ValidationMessageFor(model => model.ForemanInventory, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
#Html.LabelFor(model => model.ForemanInventory, htmlAttributes: new { #class = "control-label col-md-7 control-label-checkbox" })
</div>
<div class="form-group margin-small">
<div class="col-md-5">
<div class="checkbox control-checkbox">
#Html.EditorFor(model => model.Documents, new { htmlAttributes = new { #class = "input-control-checkbox" } })
#Html.ValidationMessageFor(model => model.Documents, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
#Html.LabelFor(model => model.Documents, htmlAttributes: new { #class = "control-label col-md-7 control-label-checkbox" })
</div>
<div class="form-group margin-small">
<div class="col-md-5">
<div class="checkbox control-checkbox">
#Html.EditorFor(model => model.StorageScanIn, new { htmlAttributes = new { #class = "input-control-checkbox" } })
#Html.ValidationMessageFor(model => model.StorageScanIn, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
#Html.LabelFor(model => model.StorageScanIn, htmlAttributes: new { #class = "control-label col-md-7 control-label-checkbox" })
</div>
<div class="form-group margin-small">
<div class="col-md-5">
<div class="checkbox control-checkbox">
#Html.EditorFor(model => model.StorageScanOut, new { htmlAttributes = new { #class = "input-control-checkbox" } })
#Html.ValidationMessageFor(model => model.StorageScanOut, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
#Html.LabelFor(model => model.StorageScanOut, htmlAttributes: new { #class = "control-label col-md-7 control-label-checkbox" })
</div>
<div class="form-group margin-small">
<div class="col-md-5">
<div class="checkbox control-checkbox">
#Html.EditorFor(model => model.ScanAtDelivery, new { htmlAttributes = new { #class = "input-control-checkbox" } })
#Html.ValidationMessageFor(model => model.ScanAtDelivery, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
#Html.LabelFor(model => model.ScanAtDelivery, htmlAttributes: new { #class = "control-label col-md-7 control-label-checkbox" })
</div>
<div class="form-group margin-small">
<div class="col-md-5">
<div class="checkbox control-checkbox">
#Html.EditorFor(model => model.AmazonRds, new { htmlAttributes = new { #class = "input-control-checkbox" } })
#Html.ValidationMessageFor(model => model.AmazonRds, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
#Html.LabelFor(model => model.AmazonRds, htmlAttributes: new { #class = "control-label col-md-7 control-label-checkbox" })
</div>
<div class="form-group margin-small">
#Html.LabelFor(model => model.AmazonRegion, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.AmazonRegion, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AmazonRegion, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
<div class="form-group margin-small">
#Html.LabelFor(model => model.AmazonIdentifier, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.AmazonIdentifier, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AmazonIdentifier, "", new { #class = "field-validation-error-tooltip" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input class="btn btn-primary" type="submit" value="Save changes" id="approve-btn" />
<button class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script>
$(function () {
$("form input").tooltipValidation({
placement: "right"
});
});
</script>
}
Script to show dialog
$(function () {
$.ajaxSetup({ cache: false });
$(document).on("click", ".modal-link", function (e) {
$('#myModalContent').load(this.href, function () {
$('#myModal').modal
(
{
keyboard: true
}, 'show'
);
bindForm(this);
});
return false;
});
$(document).on("click", "a[data-modal]", function (e)
{
$('#myModalContent').load(this.href, function ()
{
$('#myModal').modal
(
{
keyboard: true
}, 'show'
);
bindForm(this);
});
return false;
});
$(window.document).on('shown.bs.modal', '.modal', function () {
window.setTimeout(function () {
$('[autofocus]', this).focus();
}.bind(this), 100);
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
var isValid = true; // assume all OK
$('form').validate(); // perform validation on the form
$('input[type="text"]').each(function (index, item) { // could change selector to suit e.g $('input, textarea').each(..
if (!$(this).valid()) {
isValid = false; // signal errors
return false; // break out of loop
}
});
if (!isValid) {
return false; // exit
}
$('#progress').show();
$.ajax({
url: this.action,
modal: true,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#myModal').modal('hide');
$('#progress').hide();
location.reload();
alert(result.message);
}
});
return false;
});
}
Question
When I call dialog form for Edit Company I get dialog form as on Image1.
After validation $('form').validate(); // perform validation on the form
I get dialog form as on Image2. Please help me understand what do I wrong?
Image1
Image2
In Controller
public ActionResult Edit([Bind(Include = ....] Company company)
Need to use return View(company); instead of return PartialView(company)
When I call update using EF in ASP.NET it throws this error:
System.InvalidOperationException: The property 'Id' is part of the object's key information and cannot be modified.
I'd be grateful for some help with this.
Controller Code:
Save and Update method code:
[HttpPost]
public JsonResult CashVoucherSaveData(CashVoucherFormViewModel cashVoucherFormViewModel)
{
try
{
int? id = null;
Voucher voucher;
VoucherDetail voucherDetail;
if (cashVoucherFormViewModel.Id == null)
{
voucher = new Voucher();
voucherDetail = new VoucherDetail();
}
else
{
id = (int)cashVoucherFormViewModel.Id;
voucher = _voucherService.GetVoucherById((int)id);
voucherDetail = _voucherDetailService.GetVoucherDetailById((int)id);
}
// voucherFormViewModel.Debit = 33;
voucher = (Voucher)Mapper.Map(cashVoucherFormViewModel, voucher, typeof(CashVoucherFormViewModel), typeof(Voucher));
voucherDetail = (VoucherDetail)Mapper.Map(cashVoucherFormViewModel, voucherDetail, typeof(CashVoucherFormViewModel), typeof(VoucherDetail));
voucher.FinancialYearId = 2;
voucher.CompanyId = 2;
voucher.BusinessUnitId = 6;
voucher.Prefix = "3";
//voucherDetail.Serial = 3;
// voucher.Code = "23"; // voucher #
VoucherValidator voucherValidator = new VoucherValidator();
VoucherDetailValidator voucherDetailValidator = new VoucherDetailValidator();
ValidationResult validationResult = voucherValidator.Validate(voucher);
ValidationResult validationResultVoucheDetail = voucherDetailValidator.Validate(voucherDetail);
if (validationResult.IsValid && validationResultVoucheDetail.IsValid)
{
if (id == null)
{
_voucherService.CreateVoucher(voucher);
_voucherDetailService.CreateVoucherDetail(voucherDetail);
}
else
{
_voucherService.Update(voucher);
_voucherDetailService.Update(voucherDetail);
}
_voucherService.SaveVoucher();
_voucherDetailService.SaveVoucherDetail();
return new JsonSuccessResult();
}
else
{
Response.StatusCode = (int)ResponseCode.UnprocessableEntity;
return new JsonErrorResult(validationResult);
}
}
catch (Exception ex)
{
Response.StatusCode = (int)ResponseCode.UnprocessableEntity;
return new JsonErrorResult(ex.ToString());
}
}
View code:
#model RPS.WebApp.Areas.Accounting.ViewModels.CashVoucherFormViewModel
<div id="modal_backdrop" class="modal fade" data-backdrop="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class="text-center">
<h5 class="content-group-lg">Cash Payment Voucher</h5>
</div>
</div>
#using (Html.BeginForm("CashVoucherSaveData", "Vouchers", FormMethod.Post, new { #class = "stepy-basic", #id = "frmVoucher", #role = "form" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
if (ViewBag.FormMode == FormMode.Edit)
{
#Html.HiddenFor(model => model.Id)
#Html.HiddenFor(model => model.VoucherDetailId)
}
<fieldset title="1">
<legend class="text-semibold">Basic Info</legend>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Voucher Date </label>
#Html.EditorFor(model => model.VoucherDate, new { htmlAttributes = new { #class = "form-control daterange-single", #type = "text", #id = "pick_date", #placeholder = "Pick a Date" } })
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Voucher #</label>
#Html.EditorFor(model => model.Code, new { htmlAttributes = new { #class = "form-control daterange-single", #type = "text", #readonly = "true", #id = "voucherCode" } })
</div>
</div>
</div>
<div class="row">
<!--Start Debit account Field-->
<div class="col-md-12 " id="DebitAcc">
<div class="form-group">
<label>Debit Account</label>
#Html.DropDownListFor(model => model.AccountId, new SelectList(Model.Accounts, "Id", "Name"), "-- Select Debit Account --", new { #class = "select required select2insidemodal", #id = "DACC" })
</div>
</div>
<!--End Debit account Field-->
</div>
</fieldset>
<fieldset title="2">
<legend class="text-semibold">Fill Voucher</legend>
<fieldset>
<div>
<div class="col-lg-1 col-lg-offset-9" style="padding-bottom:5px;padding-left:27px;">
<button type="button" class="btn btn-info" id="addMore">
<span class="glyphicon glyphicon-plus"></span> Add More
</button>
</div>
</div>
#Html.EditorFor(model => model.Serial, new { htmlAttributes = new { #id = "serialCount" } })
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Total Debit Amount</label>
#Html.EditorFor(model => model.Debit, new { htmlAttributes = new { #class = "form-control daterange-single", #type = "text", #id = "debit", #readonly = true } })
</div>
</div>
</div>
<div id="dynamicBlock">
</div>
<hr />
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Credit Account</label>
#Html.DropDownListFor(model => model.AccountId, new SelectList(Model.Accounts, "Id", "Name"), "-- select account --", new { #class = "select required select2insidemodal", #id = "creditAccount" })
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Amount</label>
#Html.EditorFor(model => model.Credit, new { htmlAttributes = new { #class = "form-control", #type = "text", #id = "credit" } })
</div>
</div>
</div>
<div id ="HiddenTemplate" class="dN">
<div id="ROW-0" class="row">
<hr />
<div class="col-md-4">
<div class="form-group">
<label>Credit Account</label>
#Html.DropDownListFor(model => model.AccountId, new SelectList(Model.Accounts, "Id", "Name"), "-- select account --", new { #class = "select required select2insidemodal", #id = "creditAccount" })
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Amount</label>
#Html.EditorFor(model => model.Credit, new { htmlAttributes = new { #class = "form-control", #type = "text", #id = "credit" } })
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<button type="button" id="btnRemove-0" class="btn bg-teal-400 stepy-finish">Remove <i class="icon-check position-right"></i></button>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Narration</label>
#Html.EditorFor(model => model.narration, new { htmlAttributes = new { #class = "form-control", #type = "text" } })
</div>
</div>
</div>
<span> Created by:</span> <span>Created Date:</span>
</fieldset>
</fieldset>
<button type="button" id="btnSave" class="btn bg-teal-400 stepy-finish">Save <i class="icon-check position-right"></i></button>
}
</div>
</div>
</div>
Service and repository are working fine for other calls.
Please help me out with what's going on. Thanks
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
.....
});