Multiple Partial view in Same page, opened one by one on request, returns the same model on submission - asp.net-mvc-3

We are using MVC3 to develop an application. We need to create multiple entities - like customers - from the Main page. Same partial view is used to create this entity. These partial views are loaded on to Jquery model dialog(Different div tags are used) one by one on demand when clicked on a link/button. When we creates the first entity, it creates successfully and corresponding key is set to the main page. But when we try to create the second entity, the data passed to the controller is same as the first one and an exception is thrown because of unique key constraint. We tried by adding Modelstate.clear() , but no success. Now the surprise is that if we add the entities from bottom by clicking the button in reverse order (ie 3,2,1) it is getting created. Can anybody solve this?
Controller for partial View Loading and submission
public PartialViewResult _CustomerCreate()
{
CustomerViewModel customerviewmodel = new CustomerViewModel();
ModelState.Clear();
return PartialView(customerviewmodel);
}
public ActionResult _CustomerCreate(CustomerViewModel customerviewmodel)
{
CustomerBL customerBL = new CustomerBL();
ModelState.Clear();
if (ModelState.IsValid)
{
string path = Request.UrlReferrer.AbsolutePath;
}
int id = customerBL.SaveData(customerviewmodel);
string customer = Convert.ToString(customerviewmodel.FSTNAME + " " + customerviewmodel.MDLNAME + " " + customerviewmodel.LSTNAME);
return Json(new { Customerid = id, CustomerName = customer });
}
Sample script on the main page which loads partial View to Jquery Dialog
<script type="text/javascript">
$(function () {
$(".divnewnominee").dialog({
autoOpen: false, width: 800, height: 590, modal: true,
buttons: {
"Save": function () {
if ($("#CustomerFormID").validate().form()) {
$.post("/Customer/_CustomerCreate",
$("#CustomerFormID").serialize(),
function (data) {
$("#NOMINAME").val(data.CustomerName);
$("#NOMINEE").val(data.Customerid);
$(".divnewnominee").dialog("close");
});
}
},
Cancel: function () { $(this).dialog("close"); }
}
});
$(".newnominee").click(function () {
$(".divnewnominee").html("")
.dialog("option", "title", "New Customer")
.load("/Customer/_CustomerCreate", function () { $(".divnewnominee").dialog("open"); });
});
});
<script type="text/javascript">
$(function () {
$(".divfamily").dialog({
autoOpen: false, width: 800, height: 590, modal: true,
buttons: {
"Save": function () {
if ($("#CustomerFormID").validate().form()) {
$.post("/Customer/_CustomerCreate",
$("#CustomerFormID").serialize(),
function (data) {
$("#DEPOSITCUST").val(data.CustomerName);
$("#DEPOSITBY").val(data.Customerid);
$(".divfamily").dialog("close");
});
}
},
Cancel: function () { $(this).dialog("close"); }
}
});
$(".newfamily").click(function () {
$(".divfamily").html("")
.dialog("option", "title", "New Customer")
.load("/Customer/_CustomerCreate", function () { $(".divfamily").dialog("open"); });
});
});
Partial view which is loaded into the divs
#model ccs.Models.ViewModels.CustomerViewModel
#{
ViewBag.Title = "Create";
}
<h2>Customer</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="../../Scripts/ccsjs/ChooseFromList.js" type="text/javascript"> </script>
<script type="text/javascript">
$(function () {
$("#dialog").dialog({
autoOpen: false, width: 800, height: 500, modal: true,
buttons: {
"Save": function () {
if ($("#AddressLookup").validate().form()) {
$.post("/Customer/AddressLookupCreate",
$("#AddressLookup").serialize(),
function (data) {
$("#CustAddress").val(data.address);
$("#AddrID").val(data.Adressid);
$("#dialog").dialog("close");
});
}
},
Cancel: function () { $(this).dialog("close"); }
}
});
$(".Address").click(function () {
$("#dialog").html("")
.dialog("option", "title", "Address")
.load("/Customer/_AddressLookupCreate", function () { $("#dialog").dialog("open"); });
});
});
<script type="text/javascript" >
$(function () {
$("#addr").dialog({
autoOpen: false, width: 800, height: 550, modal: true,
buttons: {
"Add": function () {
if ($("#AddressLookupList").validate().form()) {
$.post("/Customer/_AddressLookupList",
$("#AddressLookupList").serialize(),
function (data) {
$("#CustAddress").val(data.address);
$("#AddrID").val(data.Adressid);
$("#addr").dialog("close");
});
}
},
Cancel: function () { $(this).dialog("close"); }
}
});
$(".searchaddr").click(function () {
$("#addr").html("")
.dialog("option", "title", "Address List")
.load("/Customer/_AddressLookupList", function () { $("#addr").dialog("open"); });
});
});
<script type="text/javascript">
$(function () {
$("#divcust").dialog({
autoOpen: false, width: 250, height: 500, modal: true
});
$("#custbtn").click(function () {
$("#divcust").html("")
.dialog("option", "title", "Customer List")
.load("/Customer/_CustomerList", function () { $("#divcust").dialog("open"); });
});
});
#using (Html.BeginForm("_CustomerCreate", "Customer", FormMethod.Post, new { id="CustomerFormID" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Create</legend>
<div style="float:left; width:100%;">
<div class="row-style">
<div class="labels">
#Html.Label("Customer Code")
</div>
<div id="Cust" class="fields">
#Html.TextBoxFor(model => model.CUSTCODE)
<div>#Html.ValidationMessageFor(model => model.CUSTCODE)</div>
</div>
<div class="labels">
#Html.Label("First Name")
</div>
<div class="fields">
#Html.EditorFor(model => model.FSTNAME)
<div> #Html.ValidationMessageFor(model => model.FSTNAME)</div>
</div>
</div>
<div class="row-style">
<div class="labels">
#Html.Label("Middle Name")
</div>
<div class="fields">
#Html.EditorFor(model => model.MDLNAME)
#Html.ValidationMessageFor(model => model.MDLNAME)
</div>
<div class="labels">
#Html.Label("Last Name")
</div>
<div class="fields">
#Html.EditorFor(model => model.LSTNAME)
#Html.ValidationMessageFor(model => model.LSTNAME)
</div>
</div>
<div class="row-style">
<div class="labels">
#Html.Label("Date of Birth")
</div>
<div class="fields">
#Html.TextBoxFor(model => model.DOB, new { #class = "datePicker", id = "DOB", style = "width:170px;" })
<div> #Html.ValidationMessageFor(model => model.DOB)</div>
</div>
<div class="labels">
#Html.Label("Gender")
</div>
<div class="fields">
#Html.DropDownListFor(model => model.Gender, new SelectList(Model.Gendr, "Key", "Value", " "), new { style = "width:205px;" })
#Html.ValidationMessageFor(model => model.Gender)
</div>
</div>
<div >
<div class="labels">
#Html.Label("Address ")
</div>
<div class="fields">
#Html.TextAreaFor(model => model.ADDRESS, new { #name = "ADDRESS", #readonly = "readonly", style = "width:170px;height:50px;" ,id="CustAddress"})
<img src="../../Content/themes/base/ccsimages/Search-icon.png" class="searchaddr" alt="Account Code" />
<img src="../../Content/themes/base/ccsimages/New.jpg" alt="Account Code" class="Address" width="16Px" height="16Px"/>
#* #Html.ActionLink("New Address", "AddressCreate")*#
#Html.ValidationMessageFor(model => model.ADDRESS)
</div>
<div class="labels">
#Html.Label("Photo ")
</div>
<div class="fields">
<p>
<input type="file" id="PhotoUpload" name="PhotoUpload" />
</p>
</div>
</div>
<div class="row-style">
<div class="labels">
#Html.Label("Pan No")
</div>
<div class="fields">
#Html.EditorFor(model => model.ITPAN)
<div>#Html.ValidationMessageFor(model => model.ITPAN)</div>
</div>
<div class="labels">
#Html.Label("Tax Circle/Ward/District")
</div>
<div class="fields">
#Html.EditorFor(model => model.WARD)
#Html.ValidationMessageFor(model => model.WARD)
</div>
</div>
<div class="row-style">
<div class="labels">
#Html.Label("Mobile No")
</div>
<div class="fields">
#Html.EditorFor(model => model.MOBILE)
#*#Html.CheckBoxFor(model => model.SNDSMS, new { #value = Model.MOBILE, #onchange = "check(value)" })*#
<div> #Html.ValidationMessageFor(model => model.MOBILE)</div>
</div>
<div class="labels">
#Html.Label("Email ")
</div>
<div class="fields">
#Html.EditorFor(model => model.EMAIL)
#*#Html.CheckBoxFor(model => model.SNDMSG)*#
<div> #Html.ValidationMessageFor(model => model.EMAIL)</div>
</div>
</div>
<div class="row-style">
<div class="labels">
#Html.Label("Phone No ")
</div>
<div class="fields">
#Html.EditorFor(model => model.PHONE)
<div> #Html.ValidationMessageFor(model => model.PHONE)</div>
</div>
<div class="labels">
#Html.Label("Fax ")
</div>
<div class="fields">
#Html.EditorFor(model => model.FAX)
<div>#Html.ValidationMessageFor(model => model.FAX)</div>
</div>
</div>
<div class="row-style">
<div class="labels">
#Html.Label("Family")
</div>
<div class="fields">
#Html.DropDownListFor(model => model.FMLY, new SelectList(Model.Famly, "Key", "Value", " "), new { style = "width:205px;" })
#Html.ValidationMessageFor(model => model.FMLY)
</div>
<div class="labels">
#Html.Label("Customer Type")
</div>
<div class="fields">
#Html.DropDownListFor(model => model.CUSTYPE, new SelectList(Model.CustTyp, "Key", "Value", " "), new { style = "width:205px;" })
#Html.ValidationMessageFor(model => model.CUSTYPE)
</div>
</div>
<div class="row-style">
<div class="labels">
#Html.Label("Repledge")
</div>
<div class="fields">
#Html.DropDownListFor(model => model.REPLEDG, new SelectList(Model.Repldg, "Key", "Value", " "), new { style = "width:205px;" })
#Html.ValidationMessageFor(model => model.REPLEDG)
</div>
<div class="labels">
#Html.Label("ID Proof Type")
</div>
<div class="fields">
#Html.DropDownListFor(model => model.IDPRTYPE, new SelectList(Model.IdProoflist, "IDPRCODE", "IDPRNAME", " "), new { style = "width:205px;" })
#Html.ValidationMessageFor(model => model.IDPRTYPE)
</div>
</div>
<div class="row-style">
<div class="labels">
#Html.Label("ID Proof No")
</div>
<div class="fields">
#Html.EditorFor(model => model.IDPNO)
#Html.ValidationMessageFor(model => model.IDPNO)
</div>
<div class="labels">
#Html.Label("ID Proof ")
</div>
<div class="fields">
<p>
<input type="file" id="IDProofUpload" name="IDProofUpload" />
</p>
</div>
</div>
<div class="row-style">
<div class="labels">
#Html.Label("Father/Husband Name")
</div>
<div class="fields">
#Html.TextBoxFor(model => model.FNAME, new { #name = "FNAME", #class = "FNAME", style = "width:170px;" })
#*<img src="../../Content/themes/base/ccsimages/Search-icon.png" alt="Account Code" onclick="openCustPickerDialog(window, document.forms[0].FCUSTID,document.forms[0].FNAME, '/Customer/_CustomerLookupIndex/')" />*#
<img src="../../Content/themes/base/ccsimages/Search-icon.png" alt="Account Code" id="custbtn"/>
#Html.ValidationMessageFor(model => model.FNAME)
#Html.HiddenFor(model => model.FID)
</div>
</div>
</div>
#Html.HiddenFor(model => model.FCUSTID, new { #name = "FCUSTID",#class="FCUSTID", style = "width:130px;" })
<div class="fields">
#Html.HiddenFor(model => model.AVASRVCE)
</div>
<div class="fields">
#Html.HiddenFor(model => model.ADDRID, new { #name = "ADDRID", style = "width:130px;",id="AddrID" })
#Html.ValidationMessageFor(model => model.ADDRID)
</div>
#*<div id="NoteListBlock">#{Html.RenderPartial("_AddressLookupCreate");}</div>*#
<div id="dialog" title="Address Lookup"></div>
<div id="addr" title="Address"></div>
<div id="divcust" title="Customer List"></div>
<div class="row-style">
<div class="errorfield">
<div class="message"> #Html.ValidationMessageFor(model => model.CUSTCODE) #Html.ValidationMessageFor(model => model.FSTNAME) #Html.ValidationMessageFor(model => model.ADDRESS)</div>
</div>
</div>
</fieldset>
}
When First Div is submitted the data gets saved properly. When Second one submits the viewmodel retains the values from the first div

We solved our issue. We added on single line of code to the Java script which invoked the partial view. The code is given below
<script type="text/javascript">
$(function () {
$(".divnewnominee").dialog({
autoOpen: false, width: 800, height: 590, modal: true,
buttons: {
"Save": function () {
if ($("#CustomerFormID").validate().form()) {
$.post("/Customer/_CustomerCreate",
$("#CustomerFormID").serialize(),
function (data) {
***$(".divnewnominee").html(data);***
$("#NOMINAME").val(data.CustomerName);
$("#NOMINEE").val(data.Customerid);
$(".divnewnominee").dialog("close");
});
}
},
Cancel: function () { $(this).dialog("close"); }
}
});
$(".newnominee").click(function () {
$(".divnewnominee").html("")
.dialog("option", "title", "New Customer")
.load("/Customer/_CustomerCreate", function () { $(".divnewnominee").dialog("open"); });
});
});

Related

Problem With .Net MVC5 Validation - Errors don't go away when they are Fixed

I am having an issue with my validation with my .Net MVC5 form. When I submit my form I get the validation summary as well as the validation messages under each field that's invalid. The problem is when I start entering information into the fields, the errors don't go away like they're supposed to. I included jquery validation min underneath my form as well as jquery validation unobtrusive min but it still doesn't work for me
This is my View:
<h2>Add</h2>
<link href="~/Content/css/result-light.css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<style id="compiled-css" type="text/css">
body {
font-family: Nunito,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji" !important;
font-size: 1rem !important;
line-height: 1.5 !important;
}
html {
font-size: 100% !important;
}
.col-xs-3 {
width: 25% !important;
}
.stepwizard-step p {
margin-top: 0px;
color: #666;
}
.stepwizard-row {
display: table-row;
}
.stepwizard {
display: table;
width: 100%;
position: relative;
}
.stepwizard-step button[disabled] {
/*opacity: 1 !important;
filter: alpha(opacity=100) !important;*/
}
.stepwizard .btn.disabled, .stepwizard .btn[disabled], .stepwizard fieldset[disabled] .btn {
opacity: 1 !important;
color: #bbb;
}
.stepwizard-row:before {
top: 14px;
bottom: 0;
position: absolute;
content: " ";
width: 100%;
height: 1px;
background-color: #ccc;
z-index: 0;
}
.stepwizard-step {
display: table-cell;
text-align: center;
position: relative;
}
.btn-circle {
width: 30px;
height: 30px;
text-align: center;
padding: 6px 0;
font-size: 12px;
line-height: 1.428571429;
border-radius: 15px;
}
.StripeElement {
box-sizing: border-box;
height: 40px;
padding: 10px 12px;
border: 1px solid transparent;
border-radius: 4px;
background-color: white;
box-shadow: 0 1px 3px 0 #e6ebf1;
-webkit-transition: box-shadow 150ms ease;
transition: box-shadow 150ms ease;
}
.StripeElement--focus {
box-shadow: 0 1px 3px 0 #cfd7df;
}
.StripeElement--invalid {
border-color: #fa755a;
}
.StripeElement--webkit-autofill {
background-color: #fefde5 !important;
}
.green {
border: solid green 1px;
}
.error {
border: solid red 1px;
}
.select2-container--default .select2-selection--single {
border: 1px solid #ccc !important;
border-radius: 4px !important;
}
.select2-container--default .select2-selection--single .select2-selection__rendered {
line-height: 1.428571429 !important;
padding: 6px 12px !important;
}
.select2-container .select2-selection--single {
height: 34px;
}
.select2-container--default .select2-selection--single .select2-selection__arrow b {
margin-top: 0;
}
/* EOS */
</style>
<script id="insert"></script>
<div class="container">
<div class="stepwizard">
<div class="stepwizard-row setup-panel">
<div class="stepwizard-step col-xs-3">
1
<p><small>Personal Information</small></p>
</div>
<div class="stepwizard-step col-xs-3">
2
<p><small>Security</small></p>
</div>
<div class="stepwizard-step col-xs-3">
3
<p><small>Church Affiliation</small></p>
</div>
<div class="stepwizard-step col-xs-3">
4
<p><small>Payment</small></p>
</div>
</div>
</div>
#using (Html.BeginForm("Create", "Login", new { #id = string.Empty }, FormMethod.Post, new { #id = "payment-form" }))
{
#Html.AntiForgeryToken()
<div class="panel panel-primary setup-content" id="step-1">
<div class="panel-heading">
<h3 class="panel-title">Personal Information</h3>
</div>
<div class="panel-body">
#Html.ValidationSummary(false, "Please fix errors before submitting the form:", new { #class = "text-danger" })
<div class="row">
<div class="form-group col-md-6">
<label class="control-label">First Name</label>
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #id = "firstName", #class = "form-control", #placeholder = "Enter First Name" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
<div class="form-group col-md-6">
<label class="control-label">Last Name</label>
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #id = "lastName", #class = "form-control", #placeholder = "Enter Last Name" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="control-label">Company</label>
#Html.EditorFor(model => model.logins.Company, new { htmlAttributes = new { #id = "company", #class = "form-control", #placeholder = "Company" } })
#Html.ValidationMessageFor(model => model.logins.Company, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="control-label">E-mail</label>
#Html.EditorFor(model => model.logins.UserName, new { htmlAttributes = new { #id = "email", #class = "form-control", #placeholder = "E-mail" } })
#Html.ValidationMessageFor(model => model.logins.UserName, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="control-label">Address</label>
#Html.EditorFor(model => model.Address, new { htmlAttributes = new { #id = "address", #class = "form-control", #placeholder = "Address" } })
#Html.ValidationMessageFor(model => model.logins.Address, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="control-label">Address 2</label>
#Html.EditorFor(model => model.Address2, new { htmlAttributes = new { #id = "address2", #class = "form-control", #placeholder = "Address2" } })
#Html.ValidationMessageFor(model => model.Address2, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label class="control-label">City</label>
#Html.EditorFor(model => model.logins.City, new { htmlAttributes = new { #id = "city", #class = "form-control", #placeholder = "City" } })
#Html.ValidationMessageFor(model => model.logins.City, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group col-md-4">
<label class="control-label">Zip</label>
#Html.EditorFor(model => model.logins.Zip, new { htmlAttributes = new { #id = "zip", #class = "form-control", #placeholder = "Zip" } })
#Html.ValidationMessageFor(model => model.logins.Zip, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="control-label">Phone</label>
#Html.EditorFor(model => model.logins.Phone, new { htmlAttributes = new { #id = "phone", #type = "tel", #class = "form-control", #placeholder = "Phone" } })
#Html.ValidationMessageFor(model => model.logins.Phone, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="control-label">Cell Phone</label>
#Html.EditorFor(model => model.logins.CellPhone, new { htmlAttributes = new { #id = "cell", #type = "tel", #class = "form-control", #placeholder = "Cell Phone" } })
#Html.ValidationMessageFor(model => model.logins.CellPhone, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="control-label">Musician Type 1</label>
#Html.DropDownListFor(model => model.musicianTypes, new SelectList(Model.musicianTypes, "id", "TypeName"), "None", new { #id = "musicianType1", #class = "form-control" })
<small class="form-text"></small>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="control-label">Musician Type 2</label>
#Html.DropDownListFor(model => model.musicianTypes, new SelectList(Model.musicianTypes, "id", "TypeName"), "None", new { #id = "musicianType2", #class = "form-control" })
<small class="form-text"></small>
</div>
</div>
<button class="btn btn-primary nextBtn pull-right" type="button">Next</button>
</div>
</div>
<div class="panel panel-primary setup-content" id="step-2">
<div class="panel-heading">
<h3 class="panel-title">Account Security</h3>
</div>
<div class="panel-body">
<div class="row">
<div class="form-group col-md-12">
<label class="control-label">Password</label>
#Html.EditorFor(model => model.logins.Password, new { htmlAttributes = new { #id = "password", #type = "password", #class = "form-control", #placeholder = "Password" } })
#Html.ValidationMessageFor(model => model.logins.Password, "", new { #class = "text-danger" })
<ul class="form-text text-muted">
<li>Must be 8-20 characters long</li>
<li>Must contain at least 1 number</li>
<li>Must contain at least 1 uppercase letter</li>
<li>Must contain at least 1 lowercase letter </li>
<li>Must contain a special character (e.g. ! ; # * %)</li>
</ul>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="control-label">Confirm Password</label>
#Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { #id = "cnfPassword", #type = "password", #class = "form-control", #placeholder = "Confirm Password" } })
#Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="control-label">Security Question</label>
#Html.DropDownListFor(model => model.chlist, new SelectList(Model.seclist, "id", "Question"), "Select", new { #id = "securityQuestion", #class = "form-control" })
<small class="form-text"></small>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="control-label">Security Answer</label>
#Html.EditorFor(model => model.logins.SecretAnswer, new { htmlAttributes = new { #id = "answer", #type = "text", #class = "form-control", #placeholder = "Security Question Answer" } })
#Html.ValidationMessageFor(model => model.logins.SecretAnswer, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="control-label">Account PIN</label>
#Html.EditorFor(model => model.logins.AccountPasscode, new { htmlAttributes = new { #id = "pin", #maxlength = "6", #type = "password", #class = "form-control", #placeholder = "Pin" } })
#Html.ValidationMessageFor(model => model.logins.AccountPasscode, "", new { #class = "text-danger" })
<small class="form-text"></small>
</div>
</div>
<button class="btn btn-primary nextBtn pull-right" type="button">Next</button>
</div>
</div>
<div class="panel panel-primary setup-content" id="step-3">
<div class="panel-heading">
<h3 class="panel-title">Church Affiliation</h3>
</div>
<div class="panel-body">
<div class="row">
<div class="form-group col-md-12">
<label class="control-label">Church Affiliation 1</label><br />
#Html.DropDownListFor(model => model.chlist, new SelectList(Model.chlist, "id", "ChurchName"), "None", new { #id = "churchAffiliation1", #class = "select2 form-control", #style = "width:100%" })
<small class="form-text"></small>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="control-label">Church Affiliation 2</label><br />
#Html.DropDownListFor(model => model.chlist, new SelectList(Model.chlist, "id", "ChurchName"), "None", new { #id = "churchAffiliation2", #class = "select2 form-control", #style = "width:100%" })
<small class="form-text"></small>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="control-label">Church Affiliation 1</label><br />
#Html.DropDownListFor(model => model.chlist, new SelectList(Model.chlist, "id", "ChurchName"), "None", new { #id = "churchAffiliation3", #class = "select2 form-control", #style = "width:100%" })
<small class="form-text"></small>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label class="control-label">Church Affiliation 4</label><br />
#Html.DropDownListFor(model => model.chlist, new SelectList(Model.chlist, "id", "ChurchName"), "None", new { #id = "churchAffiliation4", #class = "select2 form-control", #style = "width:100%" })
<small class="form-text"></small>
</div>
</div>
<button class="btn btn-primary nextBtn pull-right" type="button">Next</button>
</div>
</div>
<div class="panel panel-primary setup-content" id="step-4">
<div class="panel-heading">
<h3 class="panel-title">Payment</h3>
</div>
<div class="panel-body">
<div class="form-group">
<label for="cardName">Name on Card</label>
#Html.EditorFor(model => model.logins.Name, new { htmlAttributes = new { #id = "cardName", #class = "form-control", #placeholder = "Name On Card" } })
#Html.ValidationMessageFor(model => model.logins.Name, "", new { #class = "text-danger" })
</div>
<row>
<div class="form-group">
<label for="plan" class="control-label">Select a Plan</label><br />
#Html.DropDownListFor(model => model.subscriptionTypes, new SelectList(Model.subscriptionTypes, "id", "SubscriptionType1"), "None", new { #id = "plan", #class = "form-control" })
</div>
<div class="form-group">
<label for="card-number">
Credit or debit card
</label>
<div id="card-number">
<!-- A Stripe Element will be inserted here. -->
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<label for="card-vc">
CVC
</label>
<div id="card-cvc">
<!-- A Stripe Element will be inserted here. -->
</div>
</div>
<div class="col-md-6">
<label for="card-expiration">
Exp
</label>
<div id="card-expiration">
<!-- A Stripe Element will be inserted here. -->
</div>
</div>
</div>
</div>
<!-- Used to display form errors. -->
<div id="card-errors" role="alert"></div>
<div class="form-group">
<button class="form-control btn btn-primary" type="submit">Submit Payment</button>
</div>
</div>
</div>
}
</div>
<script type="text/javascript">
$(document).ready(function () {
var navListItems = $('div.setup-panel div a'),
allWells = $('.setup-content'),
allNextBtn = $('.nextBtn');
allWells.hide();
navListItems.click(function (e) {
e.preventDefault();
var $target = $($(this).attr('href')),
$item = $(this);
if (!$item.hasClass('disabled')) {
navListItems.removeClass('btn-success').addClass('btn-default');
$item.addClass('btn-success');
allWells.hide();
$target.show();
$target.find('input:eq(0)').focus();
}
});
allNextBtn.click(function () {
var curStep = $(this).closest(".setup-content"),
curStepBtn = curStep.attr("id"),
nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().next().children("a"),
curInputs = curStep.find("input, select"),
isValid = true;
$(".form-group").removeClass("has-error");
for (var i = 0; i < curInputs.length; i++) {
if (!curInputs[i].validity.valid) {
isValid = false;
$(curInputs[i]).closest(".form-group").addClass("has-error");
}
}
if (isValid) nextStepWizard.removeAttr('disabled').trigger('click');
});
$('div.setup-panel div a.btn-success').trigger('click');
});
</script>
<script>
$('.select2').select2();
</script>
This is my _Layout:
<!-- Custom fonts for this template-->
<link href="~/Content/AdminTemplate/vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">
<link rel="stylesheet" href="~/Content/bootstrap-datetimepicker.css" />
<!-- Custom styles for this template-->
<link href="~/Content/AdminTemplate/css/sb-admin-2.min.css" rel="stylesheet">
<link href="~/Content/AdminTemplate/vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">
<script src="~/Scripts/jquery-3.4.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<!-- Bootstrap core JavaScript-->
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Content/AdminTemplate/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="~/Content/AdminTemplate/vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Custom scripts for all pages-->
<script src="~/Content/AdminTemplate/js/sb-admin-2.min.js"></script>
<!-- Page level plugins -->
<script src="~/Content/AdminTemplate/vendor/chart.js/Chart.min.js"></script>
<!-- Page level custom scripts -->
<script src="~/Content/AdminTemplate/js/demo/chart-area-demo.js"></script>
<script src="~/Content/AdminTemplate/js/demo/chart-pie-demo.js"></script>
<!-- Page level plugins -->
<script src="~/Content/AdminTemplate/vendor/datatables/jquery.dataTables.min.js"></script>
<script src="~/Content/AdminTemplate/vendor/datatables/dataTables.bootstrap4.min.js"></script>
<!-- Page level custom scripts -->
<script src="~/Content/AdminTemplate/js/demo/datatables-demo.js"></script>
#RenderSection("stripe", required: false)
</body>
</html>
This is my controller:
public ActionResult Create()
{
if (string.IsNullOrEmpty(Convert.ToString(Session["UserName"])))
{
return RedirectToAction("Login", "Home");
}
/* var mymodel = new LoginSecurityQuestionsViewModel();
mymodel.logins = db.logins.ToList();
ViewBag.securityquestions = db.secretquestions.ToList();
ViewBag.churches = db.churches.ToList();
ViewBag.subscriptionTypes = db.subscriptiontypes.ToList();
ViewBag.musicianTypes = db.musiciantypes.ToList();
return View(mymodel);*/
LoginSecurityQuestionsViewModel multi_Dropdownlist = new LoginSecurityQuestionsViewModel
{
seclist = GetSecurityQuestionList(),
chlist = GetChurchList(),
subscriptionTypes = GetSubscriptionTypes(),
musicianTypes = GetMusicianTypes()
};
return View(multi_Dropdownlist);
}
// POST: login/Create
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
public ActionResult Create(ChargeDTO chargeDto)
{
if (ModelState.IsValid == false)
{
LoginSecurityQuestionsViewModel multi_Dropdownlist = new LoginSecurityQuestionsViewModel
{
seclist = GetSecurityQuestionList(),
chlist = GetChurchList(),
subscriptionTypes = GetSubscriptionTypes(),
musicianTypes = GetMusicianTypes()
};
return View(multi_Dropdownlist);
}
}
I can't figure out why the errors don't go away when I fix the validation errors. Also, each time my form loads it displays Please fix errors before submitting the form: in red. The errors only go away when I click submit. Maybe this has something to do with my javascript on the view page?

ASP.NET Core MVC Ajax post on success returning html page and then in the page shows only a json?

Basically I call the SendInvoince method from the controller and an invoice is sent!
The problem is with the ajax post upon success the data is the html page instead of the json returned from the controller method, poping up the swal error and after 1 sec it refreshes the page showing a page with only the json returned by the controller!???? Why? What is happening?
This is my controller:
[HttpPost]
public IActionResult SendInvoice(Document document)
{
bool success = false;
string errorMessage = null;
string session = GetSession();
document.Docktype = "4";
try
{
document.Id = InsertDocumentHeader(document, session);
InsertDocumentLine(document, session);
document.Id = CloseDocument(document, session);
Client client = GetClient(session, document.NIF);
SendDocumentPDF2Email(document, session, client.Email);
success = true;
}
catch (Exception e)
{
errorMessage = e.Message;
}
return Json(new { success, Error = errorMessage });
}
This is my view:
#{
ViewData["Title"] = "Home Page";
}
#model WebApplication2.Controllers.HomeController.HomeModel
<style>
.required:after {
content: " *";
color: red;
}
.control-label {
margin-left: 2%;
}
</style>
<div>
<div id="AddClientModal" class="modal">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Client</h4>
<button type="button" class="close" data-dismiss="modal">X</button>
</div>
<br />
<form action="#Url.Action("CreateClient", "Home")" method="post" id="addClientForm">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<b style="color:red; margin-left: 2%; ">* </b>Required field
<br />
<div class="form-group">
#Html.LabelFor(model => model.Client.NIF,
htmlAttributes: new { #class = "control-label required" })
<div class="col-md-8">
#Html.EditorFor(model => model.Client.NIF,
new { htmlAttributes = new { #class = "form-control", #id = "clientNIF" } })
#Html.ValidationMessageFor(model => model.Client.NIF,
"", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.Name,
htmlAttributes: new { #class = "control-label required" })
<div class="col-md-8">
#Html.EditorFor(model => model.Client.Name,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Name,
"", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.Address,
htmlAttributes: new { #class = "control-label required" })
<div class="col-md-8">
#Html.EditorFor(model => model.Client.Address,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Address,
"", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.Locality,
htmlAttributes: new { #class = "control-label required" })
<div class="col-md-8">
#Html.EditorFor(model => model.Client.Locality,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Locality,
"", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.PostalCode,
htmlAttributes: new { #class = "control-label required" })
<div class="col-md-8">
#Html.EditorFor(model => model.Client.PostalCode,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.PostalCode,
"", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.Email,
htmlAttributes: new { #class = "control-label required" })
<div class="col-md-8">
#Html.EditorFor(model => model.Client.Email,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Email,
"", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.Fax,
htmlAttributes: new { #class = "control-label" })
<div class="col-md-8">
#Html.EditorFor(model => model.Client.Fax,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Fax,
"", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.Phone,
htmlAttributes: new { #class = "control-label required" })
<div class="col-md-8">
#Html.EditorFor(model => model.Client.Phone,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Phone,
"", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.Obs,
htmlAttributes: new { #class = "control-label" })
<div class="col-md-8">
#Html.EditorFor(model => model.Client.Obs,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Obs,
"", new { #class = "text-danger" })
</div>
</div>
</form>
<div class="modal-footer">
<button id="btnAddClientFormSubmit" class="btn btn-success" form="addClientForm" type="button">Create</button>
<button id="btnAddClientFormCancel" class="btn btn-danger" type="button">Cancel</button>
</div>
</div>
</div>
</div>
<div>
<div id="SendInvoiceModal" class="modal">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Send Invoice</h4>
<button type="button" class="close" data-dismiss="modal">X</button>
</div>
<br />
<form action="#Url.Action("SendInvoice", "Home")" method="post" id="SendInvoiceForm">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<b style="color:red; margin-left: 2%; ">* </b>Required field
<br />
<div class="form-group">
#Html.LabelFor(model => model.Client,
htmlAttributes: new { #class = "control-label required" })
<div class="col-md-8">
#Html.DropDownListFor(model => model.Document.NIF,
Model.Clients.Select(x => new SelectListItem { Text = x.Name, Value = x.NIF }), null,
new { htmlAttributes = new { #class = "form-control", #id = "optClientNIF" } })
#Html.ValidationMessageFor(model => model.Document.NIF,
"", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Document.Obs,
htmlAttributes: new { #class = "control-label" })
<div class="col-md-8">
#Html.EditorFor(model => model.Document.Obs,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Document.Obs,
"", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Document.DocRef,
htmlAttributes: new { #class = "control-label" })
<div class="col-md-8">
#Html.EditorFor(model => model.Document.DocRef,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Document.DocRef,
"", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Document.Qt,
htmlAttributes: new { #class = "control-label" })
<div class="col-md-8">
#Html.EditorFor(model => model.Document.Qt,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Document.Qt,
"", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Document.Price,
htmlAttributes: new { #class = "control-label" })
<div class="col-md-8">
#Html.EditorFor(model => model.Document.Price,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Document.Price,
"", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Document.Tax,
htmlAttributes: new { #class = "control-label" })
<div class="col-md-8">
#Html.EditorFor(model => model.Document.Tax,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Document.Tax,
"", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Document.ProdDesc,
htmlAttributes: new { #class = "control-label" })
<div class="col-md-8">
#Html.EditorFor(model => model.Document.ProdDesc,
new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Document.ProdDesc,
"", new { #class = "text-danger" })
</div>
</div>
</form>
<div class="modal-footer">
<button id="btnSendInvoiceFormSubmit" class="btn btn-success" form="SendInvoiceForm" type="submit">Create</button>
<button id="btnSendInvoiceFormCancel" class="btn btn-danger" type="button">Cancel</button>
</div>
</div>
</div>
</div>
<div>
<button id="AddClientModalBtn" class="btn btn-primary" type="button">Insert Client</button>
<button id="SendInvoiceModalBtn" class="btn btn-primary" type="button">Send Invoice</button>
</div>
<div class="card shadow mb-4" style="margin-top: 3%;">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">Clients</h6>
</div>
<div class="card-body" style="margin-bottom: 1rem">
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>#Html.DisplayNameFor(model => model.Client.NIF)</th>
<th>#Html.DisplayNameFor(model => model.Client.Name)</th>
<th>#Html.DisplayNameFor(model => model.Client.Address)</th>
<th>#Html.DisplayNameFor(model => model.Client.Locality)</th>
<th>#Html.DisplayNameFor(model => model.Client.PostalCode)</th>
<th>#Html.DisplayNameFor(model => model.Client.Email)</th>
<th>#Html.DisplayNameFor(model => model.Client.Fax)</th>
<th>#Html.DisplayNameFor(model => model.Client.Phone)</th>
<th>#Html.DisplayNameFor(model => model.Client.Obs)</th>
</tr>
</thead>
<tfoot>
<tr>
<th>#Html.DisplayNameFor(model => model.Client.NIF)</th>
<th>#Html.DisplayNameFor(model => model.Client.Name)</th>
<th>#Html.DisplayNameFor(model => model.Client.Address)</th>
<th>#Html.DisplayNameFor(model => model.Client.Locality)</th>
<th>#Html.DisplayNameFor(model => model.Client.PostalCode)</th>
<th>#Html.DisplayNameFor(model => model.Client.Email)</th>
<th>#Html.DisplayNameFor(model => model.Client.Fax)</th>
<th>#Html.DisplayNameFor(model => model.Client.Phone)</th>
<th>#Html.DisplayNameFor(model => model.Client.Obs)</th>
</tr>
</tfoot>
<tbody>
#foreach (Client row in Model.Clients)
{
<tr id="#row.NIF">
<td>#row.NIF</td>
<td>#row.Name)</td>
<td>#row.Address</td>
<td>#row.Locality</td>
<td>#row.PostalCode</td>
<td>#row.Email</td>
<td>#row.Fax</td>
<td>#row.Phone</td>
<td>#row.Obs</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="~/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="~/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript" src="~/lib/limonte-sweetalert2/sweetalert2.min.js"></script>
#*<script type="text/javascript" src="~/lib/datatables/js/jquery.dataTables.js"></script>
<script type="text/javascript" src="~/lib/datatables/js/dataTables.bootstrap4.js"></script>*#
#{await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
<script>
function CheckNIF(NIF) {
var isValid = false;
const arrayNIF = Array.from(String(NIF), Number);
var sum = 0;
var multi = 9;
for (var i = 0; i < arrayNIF.length - 1; i++) {
sum += arrayNIF[i] * multi;
multi--;
}
var result = sum % 11;
if (result == 0 || result == 1) {
result = 0;
}
else {
result = 11 - result;
}
if (result == arrayNIF[8]) {
isValid = true;
}
else {
isValid = false;
}
return isValid;
}
$(document).ready(function () {
$('#AddClientModalBtn').click(function () {
$("#AddClientModal").modal('show');
});
$('#btnAddClientFormSubmit').click(function () {
var NIF = document.getElementById('clientNIF').value
if (CheckNIF(NIF)) {
$("#addClientForm").submit();
}
else {
console.log("Error");
swal.fire({
position: 'top',
type: 'error',
title: 'Invalid NIF',
text: 'Please enter a valid NIF',
allowOutsideClick: false,
});
}
});
$('#btnAddClientFormCancel').click(function () {
$("#AddClientModal").modal('hide');
$("#addClientForm").trigger('reset');
});
$('#SendInvoiceModalBtn').click(function () {
$("#SendInvoiceModal").modal('show');
});
$('#btnSendInvoiceFormCancel').click(function () {
$("#SendInvoiceModal").modal('hide');
$("#SendInvoiceForm").trigger('reset');
});
$(function () {
$('#addClientForm').submit(function () {
$.ajax({
url: this.url,
type: this.method,
data: $(this).serialize(),
success: function (data) {
if (data.success) {
Swal.fire({
position: 'top-end',
type: 'success',
title: 'Client added.',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
});
console.log("Success");
}
else {
Swal.fire({
type: 'error',
text: 'Error adding client. If the problem persists, please contact the support.',
allowOutsideClick: false,
});
console.log("Server Error");
}
},
error: function () {
console.log("Request failed");
}
});
});
});
$(function () {
$('#SendInvoiceForm').submit(function (event) {
event.preventDefault();
$.ajax({
url: this.url,
type: this.method,
data: $(this).serialize(),
success: function (data) {
console.log("HELLO");
console.log(data);
console.log(data.length);
console.log(data.success);
if (data.success) {
Swal.fire({
position: 'top-end',
type: 'success',
title: 'Invoice sent.',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
});
console.log("Success");
}
else {
Swal.fire({
type: 'error',
text: 'Error sending invoice. If the problem persists, please contact the support.',
allowOutsideClick: false,
});
console.log("Server Error");
}
},
error: function () {
console.log("Request failed");
}
});
});
});
});
</script>
this are the console.logs (console.log(data), console.log(data.lenght), console.log(data.success)):
And this is the page after the ajax post:
Best regards!!
After some time spent with this I found out that using: this.url for ajax url was the problem!!!!
before:
$(function () {
$('#SendInvoiceForm').submit(function (event) {
event.preventDefault();
$.ajax({
url: this.url,
type: this.method,
data: $(this).serialize(),
SndInvoiceForm as the action:
<form action="#Url.Action("SendInvoice", "Home")" method="post" id="SendInvoiceForm">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<b style="color:red; margin-left: 2%; ">* </b>Required field
Don't know why it doesn't work??
After:
$(function () {
$('#SendInvoiceForm').submit(function (event) {
event.preventDefault();
$.ajax({
url: '#Url.Action("SendInvoice", "Home")',
type: this.method,
data: $(this).serialize(),
Now Works!!!!
If someone knows why, please let me know!!

Use ajax in asp.net mvc 5 in a tab

I want to use ajax to update the content of a TAB and it doesn't work, when I press the buton submit i update all the page. I don't know how to solve it.
Thanks.
Controller PeticioUsuarisController:
// POST: PeticioUsuaris/_Demanar
// 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 _Demanar([Bind(Include = "Nom,PrimerCognom,SegonCognom")] PeticioUsuari peticioUsuari)
{
if (ModelState.IsValid)
{
peticioUsuari.IdUsuariFaPeticio = 1;
db.PeticioUsuari.Add(peticioUsuari);
db.SaveChanges();
return PartialView("_PeticioCorrecte");
}
return PartialView("_PeticioCorrecte");
}
View Index.cshtml:
#{
ViewBag.Title = "";
}
<!-- Tab Buttons -->
<ul id="tabstrip" class="nav nav-tabs" role="tablist">
<li class="active">Demanar</li>
<li>Acceptar</li>
</ul>
<!-- Tab Content Containers -->
<div class="tab-content">
<div class="tab-pane fade in active" id="_Demanar">#Html.Partial("_Demanar")</div>
<div class="tab-pane fade" id="_AcceptarPeticio"></div>
</div>
#section scripts {
<script>
$('#tabstrip a').click(function (e) {
e.preventDefault()
var tabID = $(this).attr("href").substr(1);
$(".tab-pane").each(function () {
console.log("clearing " + $(this).attr("id") + " tab");
$(this).empty();
});
//$("#" + tabID).load("/#ViewContext.RouteData.Values["controller"]/" + tabID)
$.ajax({
url: "/#ViewContext.RouteData.Values["controller"]/" + tabID,
cache: false,
type: "get",
dataType: "html",
success: function (result) {
$("#" + tabID).html(result);
}
})
$(this).tab('show')
});
</script>
}
View _Demanar:
#model Peticions.Models.PeticioUsuari
#{
AjaxOptions options = new AjaxOptions
{
HttpMethod = "Post",
UpdateTargetId = "content",
InsertionMode = InsertionMode.InsertAfter
};
}
#using (Ajax.BeginForm("_Demanar", "PeticioUsuaris", null, options))
{
#Html.AntiForgeryToken()
<div class="form-horizontal tabs">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Nom, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Nom, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Nom, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PrimerCognom, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PrimerCognom, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PrimerCognom, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SegonCognom, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SegonCognom, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SegonCognom, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default"/>
</div>
</div>
</div>
}
<div id="content"></div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
View _PeticioCorrecte:
#model Peticions.Models.PeticioUsuari
<div class="alert alert-success">
<a href="#Url.Action("Index", "PeticioUsuaris", new { id = UrlParameter.Optional })">
PeticiĆ³ enviada correctament! Clica aquĆ­ per a crear-ne un altre.
</a>
</div>
try this
#{
AjaxOptions options = new AjaxOptions
{
HttpMethod = "Post",
UpdateTargetId = "formContent"
};
}
#using (Ajax.BeginForm("_AcceptarPeticio", "PeticioUsuaris", null,options ))
{
}

Display message using view bag without refreshing view

I have a view A From ControllerA Which has two buttons 1. Create 2. Update
Upon clicking update or Create its opening a new partial viewB As popup from another controller B.
What iam trying to get is If a record is created successfully in b I am now closing the popup. Apart from closing the popup I want to display a message in view A.
I am trying like this:
Controller B
public ActionResult Create(FormCollection args)
{
var obj = new ProjectManagernew();
var res = new ProjectViewModelNew();
try
{
UpdateModel(res);
if (obj.AddUpdateOrderField(res))
{
ViewBag.RecordAdded = true;
ViewBag.Message = "Project Added Successfully";
}
return View(res);
}
catch (Exception)
{
//ModelState.AddRuleViolations(res.GetRuleViolations());
return View(res);
}
}
And in the view A:
#if(ViewBag.Message!=null)
{
#ViewBag.Message
}
View B:
#model DreamTrade.Web.BL.ViewModels.ProjectViewModelNew
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout_Popup.cshtml";
}
#if (ViewBag.RecordAdded != null && (bool)ViewBag.RecordAdded)
{
<script type="text/javascript">
parent.$.nmTop().close();
$('#jqgprojectnew').text("Record added successfully");//jqgprojectnew is the name of grid in view A
</script>
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Project</legend>
#Html.HiddenFor(model => model.ProjectID)
<div class="editor-label">
#Html.LabelFor(model => model.ProjectDetail)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProjectDetail)
#Html.ValidationMessageFor(model => model.ProjectDetail)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProjectRef)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProjectRef)
#Html.ValidationMessageFor(model => model.ProjectRef)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProjectName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProjectName)
#Html.ValidationMessageFor(model => model.ProjectName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.StatusList)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.ProjectStatusId,new SelectList(Model.StatusList,"SourceStatusId","Description"),"Please Select")
#Html.ValidationMessageFor(model => model.ProjectStatusId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CustomerList)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Id,new SelectList(Model.CustomerList,"Id","Name"),"Please Select")
#Html.ValidationMessageFor(model => model.Id)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<div>
Back to list
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
please let me know where iam doing wrong
Include a label field where you want to show the message.
<label id=mylabel></label>// Add this before jqgrid
Modify the code to:
#if (ViewBag.RecordAdded != null && (bool)ViewBag.RecordAdded)
{
<script type="text/javascript">
parent.$.nmTop().close();
$('#mylabel').text("Record added successfully");
</script>
}

ASP.Net MVC 3 Jquery UI Dialog Form

I am trying to make a popup dialog to allow the user to fill in a form.
When they click submit I want to submit the form.
I figured out how to make the modal popup but cannot figure out how to get it to submit the form when the form is clicked. Does anyone know how to do this?
#using (Html.BeginForm())
{
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
#Html.LabelFor(m => m.UserName)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Password)
</div>
<div class="editor-field">
#Html.PasswordFor(m => m.Password)
#Html.ValidationMessageFor(m => m.Password)
</div>
<div class="editor-label">
#Html.CheckBoxFor(m => m.RememberMe)
#Html.LabelFor(m => m.RememberMe)
</div>
<p>
<input type="submit" value="Log On" />
</p>
</fieldset>
</div>
}
<script type="text/javascript">
$(document).ready(function () {
$("#dialog-form").dialog({
modal: true,
buttons: {
"Submit": function () {
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
});
</script>
You need to make sure you have a valid POST method in your controller for the form to submit to. Your form here looks valid as long as you aren't expecting the dialog's submit button to submit the form. If that is the case then you will need to give the form an ID and call submit from your function for the dialog "Submit" button.
<div id="dialog-form">
#using (Html.BeginForm("LogOn", "Account", FormMethod.Post, new { id = "LogOnForm" })) {
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
#Html.LabelFor(m => m.UserName)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Password)
</div>
<div class="editor-field">
#Html.PasswordFor(m => m.Password)
#Html.ValidationMessageFor(m => m.Password)
</div>
<div class="editor-label">
#Html.CheckBoxFor(m => m.RememberMe)
#Html.LabelFor(m => m.RememberMe)
</div>
<p>
<input type="submit" value="Log On" style="display:none;" />
</p>
</fieldset>
</div>
}
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#dialog-form").dialog({
modal: true,
buttons: {
"Submit": function () {
$("#LogOnForm").submit();
},
Cancel: function () {
$(this).dialog("close");
}
}
});
});
</script>

Resources