jQuery submit() is not called - javascript

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;
})
});

Related

unable to redirect to the line from where the action method is called in mvc

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

The property 'Id' is part of the object's key information and cannot be modified using EF in ASP.Net

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

json data being received as null when sent to mvc controller

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

javascript click function not working in asp.net mvc

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

Updating part of view after submitting a post using jquery ajax in asp.net mvc

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
.....
});

Categories

Resources