MVC AddModelError custom error not shown in Ajax form - asp.net-mvc

I have a login form in which I would like to show custom error like "User not exists" same way as ValidationMessageFor messages works.
I am adding the custom error in the controller, but it is not shown in the form.
In order to show validation messages in an Ajax form I used the techinque of returning a login PartialView which I return from the controller
Thanks for the help!
Controller:
[HttpPost]
public ActionResult Login(Login login)
{
if (!ModelState.IsValid) //Check for validation errors
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return PartialView("_login", login);
}
ActiveDirectoryDAL.ADQueries ad = new ActiveDirectoryDAL.ADQueries();
var userName = login.UserName.ToLower().Trim();
var password = login.Password.Trim();
var isValidUser = ad.Authenticate(userName, password);
if (!isValidUser)
{
ModelState.AddModelError(string.Empty, "Login failed");
return PartialView("_login", login);
}
FormsAuthentication.SetAuthCookie(login.UserName, false);
return Json(new { RedirectUrl = Url.Action("Index", "Home") });
}
The View
#model PushNotificationWebSite.Models.Login
#{
ViewBag.Title = "Login";
Layout = "";
}
<html>
<head>
<link href="~/Content/login.css" rel="stylesheet" />
#Styles.Render("~/Content/bootstrap/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
</head>
<script type="text/javascript">
function OnSuccess(data) {
if (data.RedirectUrl)
window.location.href = data.RedirectUrl;
}
function OnLoginFailure(data) {
debugger;
$('#login').html(data.responseText);
}
</script>
<body id="LoginForm">
<div class="container">
<h1 class="form-heading">login Form</h1>
<div class="login-form">
<div class="main-div">
<div class="panel">
<h2>Admin Login</h2>
<p>Please enter your username and password</p>
</div>
#using (Ajax.BeginForm("Login", "Account", new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
LoadingElementId = "loader",
OnSuccess = "OnSuccess",
OnFailure = "OnLoginFailure"
}, new { id = "login" }))
{
#Html.ValidationSummary(true)
<div class="form-group">
#Html.TextBoxFor(model => model.UserName, new { #class = "form-control", autocomplete = "off", placeholder = "Username" })
</div>
<div class="form-group">
#Html.TextBoxFor(model => model.Password, new { #class = "form-control", autocomplete = "off", type = "password", placeholder = "Password" })
#Html.ValidationMessageFor(m => m.Password, "", new { #class = "text-danger" })
</div>
<button type="submit" class="btn btn-primary">Login</button>
}
<div id="loader" class="loader">
<img class="center" src="~/Images/ajax-loader.gif" />
</div>
</div>
</div>
</div>
</body>
</html>
Partial View:
#model PushNotificationWebSite.Models.Login
#using (Ajax.BeginForm("Login", "Account", new AjaxOptions
{
HttpMethod = "POST",
LoadingElementId = "loader",
OnSuccess = "OnSuccess",
OnFailure = "OnLoginFailure"
}, new { id = "login" }))
{
#Html.ValidationSummary(true)
<div class="form-group">
#Html.TextBoxFor(model => model.UserName, new { #class = "form-control", autocomplete = "off", placeholder = "Username" })
#Html.ValidationMessageFor(m => m.UserName, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.TextBoxFor(model => model.Password, new { #class = "form-control", autocomplete = "off", type = "password", placeholder = "Password" })
#Html.ValidationMessageFor(m => m.Password, "", new { #class = "text-danger" })
</div>
<button type="submit" class="btn btn-primary">Login</button>
}

Instead of using string.Empty as key name, you can assign any string as key name to the custom ModelState error. Change ModelState.AddModelError() from this:
ModelState.AddModelError(string.Empty, "Login failed");
to this example:
ModelState.AddModelError("LoginFailed", "Login failed");
Afterwards, put a ValidationMessage helper inside partial view with same key name as assigned in ModelState.AddModelError like example below:
#* message without styling *#
#Html.ValidationMessage("LoginFailed")
#* message with styling *#
#Html.ValidationMessage("LoginFailed", new { #class = "text-danger" })
Or use ViewData.ModelState to display it, again with same key name:
#ViewData.ModelState["LoginFailed"].Errors[0].ErrorMessage
Note:
In addition to InsertionMode.Replace setting, you may consider using UpdateTargetId to update partial view form contents when validation failed:
#using (Ajax.BeginForm("Login", "Account", new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
LoadingElementId = "loader",
UpdateTargetId = "elementId", // here you can set HTML element ID to update
OnSuccess = "OnSuccess",
OnFailure = "OnLoginFailure"
}, new { id = "login" }))
{
// form contents
}

I found the root cause.
I forgot to add Response.StatusCode = (int)HttpStatusCode.BadRequest;
before sending return PartialView("_login", login);
The server sent resonse OK 200 so validators did not triggered

Related

MVC POP Up and PostBack

I have a MVC c#, signalR project where Agent follow below steps in Application
Login To application. Once login success application hides Login div panel & displays list of campaign & telephony buttons
Application displays list of campaigns agent is assigned to
Application displays button in front of each campaign to set Ready / Not Ready in campaign. In this case it is RestAPI & Telemarketing
If agent need to set himself not ready in campaign it opens popup window with list not ready reasons.
Issue is :
When Agent select reason and submit it application post back it lost view and reset to login window.
Controller action after submit of breakreason in PopUp window:
public ActionResult SetBreak(breakReasonModel form)
{
string tok=form.accessToken;
string cmp = form.campaign;
string selreason = "";
for (int i=0;i < form.arrReasons.Length;i++)
{
selreason = form.arrReasons[i];
}
SetBreak obj = new SetBreak();
System.Collections.Generic.List<ISCampaigns> IScampaignNames = new System.Collections.Generic.List<ISCampaigns>();
IScampaignNames = obj.setNotReadyInCampaign(tok, cmp, selreason);
return RedirectToAction("Index");
}
PopUp Partial View :
#using Altitude.IntegrationServer.RestApiWebApp.Models
#model Altitude.IntegrationServer.RestApiWebApp.Models.breakReasonModel
<div id="divBreakReasons">
#using (Html.BeginForm("SetBreak", "Home"))
{
#Html.ListBoxFor(m => m.arrReasons, Model.reasonsMultiSelectList, new { #class = "form-control" })
#Html.TextBoxFor(model => model.accessToken, new { id = "txtaccessToken" })
#Html.TextBoxFor(model => model.campaign, new { id = "txtcampaign" })
<br />
<button id="btn" type="submit" class="btn btn-block bg-primary" value="Submit" >Submit</button>
<br />
}
</div>
Index.chtml
<div class="row">
<div class="col-md-4 table-responsive" id="telButtons">
<table id="tblTelephony" class="table">
--Telephony Buttons
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="col-md-4 table-responsive">
<p id="demo"></p> // Campaign table with Ready/Not Ready buttons
</div>
</div>
//ajax call to open popup
<div id="dialog" style="display: none"></div>
<script type="text/javascript">
function getBreak(nrReason) {
$("#dialog").dialog({
autoOpen: false,
modal: true,
});
$.ajax({
type: "POST",
url: "#Url.Action("popupBreak","Home")",
data: '{breakReason : "' + dataToSend + '",accessToken : "' +acc+ '",campaign : "' + cmp + '"}',
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (response) {
$('#dialog').html(response);
$('#dialog').dialog('open');
console.log(response);
},
failure: function (response) {
},
error: function (response) {
}
});
}
</script>
It does exactly what you coded. If you need to return result to current view you should use ajax call that will return action result.
example
#using (Ajax.BeginForm("Action", "Controller", FormMethod.Post, new AjaxOptions() { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "YourTargetForResult" }, new { #id = "ajaxForm" }))
You must reference jquery.unobtrusive-ajax.js to receive postback in current view.
Example based on your comment:
<input type="hidden" id="hdnResponseMessage" /> // add dom object where response hits
#using (Ajax.BeginForm("SetBreak", "YourControllerName", FormMethod.Post, new AjaxOptions() { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "hdnResponseMessage" }, new { #id = "form" }))
{
#Html.ListBoxFor(m => m.arrReasons, Model.reasonsMultiSelectList, new { #class = "form-control" })
#Html.TextBoxFor(model => model.accessToken, new { id = "txtaccessToken" })
#Html.TextBoxFor(model => model.campaign, new { id = "txtcampaign" })
<br />
<button id="btn" type="submit" class="btn btn-block bg-primary" value="Submit" >Submit</button>
<br />
}
Conroller:
[HttpPost]
public JsonResult SetBreak(breakReasonModel form)
{
string tok=form.accessToken;
string cmp = form.campaign;
string selreason = "";
for (int i=0;i < form.arrReasons.Length;i++)
{
selreason = form.arrReasons[i];
}
SetBreak obj = new SetBreak();
System.Collections.Generic.List<ISCampaigns> IScampaignNames = new System.Collections.Generic.List<ISCampaigns>();
IScampaignNames = obj.setNotReadyInCampaign(tok, cmp, selreason);
return Json("SetBreak");
}
jQuery set listener in document ready:
// add dom object listener
$('#hdnResponseMessage').bind('DOMNodeInserted', function () {
var txt = $('#hdnResponseMessage').text();
if (txt == 'SetBreak')
{
//do your stuff here;
}
});

ASP.NET MVC return 500 for dropdownlist cascading

Am using it for cascading dropdownlist for country and state. When I click on
country dropdownlist that suppose to display states, I got 500 server error. Please help me
The error occurs when I click the Country dropdownlist
[HttpPost]
[ValidateAntiForgeryToken] //this is to prevent CSRF attack
public ActionResult Create(CITIES ci)
{
List<COUNTRIES> allCountry = new List<COUNTRIES>();
List<STATES> allState = new List<STATES>();
using (AdminEntities dc = new AdminEntities())
{
allCountry = dc.COUNTRIES.OrderBy(a => a.COUNTRY_NAME).ToList();
if (ci != null && ci.COUNTRY_ID > 0)
{
allState = dc.STATES.Where(a => a.COUNTRY_ID.Equals(ci.COUNTRY_ID)).OrderBy(a => a.STATE_NAME).ToList();
}
}
ViewBag.COUNTRY_ID = new SelectList(allCountry, "COUNTRY_ID", "COUNTRY_NAME", ci.COUNTRY_ID);
ViewBag.STATE_ID = new SelectList(allState, "STATE_ID", "STATE_NAME", ci.STATE_ID);
if (ModelState.IsValid)
{
using (AdminEntities dc = new AdminEntities())
{
dc.CITIES.Add(ci);
dc.SaveChanges();
ModelState.Clear();
ci = null;
ViewBag.Message = "Successfully Saved";
}
}
else
{
ViewBag.Message = "Failed! Please try again";
}
return View(ci);
}
[HttpGet]
public JsonResult GetStates(string countryID = "")
{
// List<COUNTRIES> allCountry = new List<COUNTRIES>();
List<STATES> allState = new List<STATES>();
int ID = 0;
if (int.TryParse(countryID, out ID))
{
using (AdminEntities dc = new AdminEntities())
{
allState = dc.STATES.Where(a => a.COUNTRY_ID.Equals(ID)).OrderBy(a => a.STATE_NAME).ToList();
}
}
if (Request.IsAjaxRequest())
{
return new JsonResult
{
Data = allState,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
return new JsonResult
{
Data = "Not valid request",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
view
#model BPP.CCSP.Admin.Web.Models.CITIES
Create
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="form-horizontal">
<h4>CITIES</h4>
<hr />
#if(ViewBag.message != true)
{
<div style="border:solid 1px black">
#ViewBag.message
</div>
}
<div class="form-group">
#Html.LabelFor(model => model.COUNTRY_ID, "COUNTRY_ID", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#* #Html.DropDownListFor(model=>model.COUNTRY_ID, new SelectList(string.Empty, "Value", "Text"), "Please select a country", new { #style = "width:250px;" }) *#
#Html.DropDownListFor(model => model.COUNTRY_ID, #ViewBag.COUNTRY_ID as SelectList,"Select Country")
#Html.ValidationMessageFor(model => model.COUNTRY_ID)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.STATE_ID, "STATE_ID", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#* #Html.DropDownListFor(model => model.STATE_ID, new SelectList(string.Empty, "Value", "Text"), "Please select a state", new { #style = "width:250px;" }) *#
#Html.DropDownListFor(model => model.STATE_ID, #ViewBag.STATE_ID as SelectList, "Select State")
#Html.ValidationMessageFor(model => model.STATE_ID)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CITY_NAME, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CITY_NAME)
#Html.ValidationMessageFor(model => model.CITY_NAME)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script language="javascript">
$(document).ready(function () {
$("#COUNTRY_ID").change(function () {
//this will call when country dropdown select change
var countryID = parseInt($("#COUNTRY_ID").val());
if (!isNaN(countryID))
{
var ddState = $("#STATE_ID");
ddState.empty(); //this line is to clear all items from statee dropdown
ddState.append($("<option></option>").val("").html("Select State"));
//here i will call controller action via jquery to load state for selected country
$.ajax({
url: "#Url.Action("GetStates","CITIES")",
type: "GET",
data: {countryID : countryID},
dataType: "json",
success: function (data)
{
$.each(data, function (i, val) {
ddState.append(
$("<option></option>").val(val.STATE_ID).html(val.STATE_NAME)
);
});
}
,
error: function ()
{
alert("Error!");
}
});
}
});
});
</script>
}
Please what do I do
can you try
var data = {"countryID" : countryID};
$.ajax({
url: '#Url.Content("~/CITIES/GetStates")',
type: "GET",
contentType: 'application/json',
data:JSON.stringify(data),
});
and then debug GetStates action and if you get error there you will get normally 500 server error

Load partial view after button click

I have this issue, have search a lot but with now correct answer.
I have a contact form in the footer, on my _Layout page, but when I clicked the button the partial view is open in a new page.
I have remember to include the jquery.unobtrusive-ajax.js. Here is what I have.
Controller :
[HttpGet]
public ActionResult Call()
{
return PartialView("_PartialFooter");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Call(CallMe callMe)
{
if(ModelState.IsValid)
{
}
return PartialView("_PartialFooter");
}
_Layout the scripts is above the Body tag in the bottom
#using (Ajax.BeginForm("Call", "Home", new AjaxOptions { UpdateTargetId = "result" }))
{
<div id="result" class="margin-bottom-5">
#Html.Action("Call", "Home")
</div>
<button class="btn btn-common-small margin-bottom-10 pull-right" type="submit">Send</button>
}
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#Scripts.Render("~/bundles/myscripts")
#RenderSection("scripts", required: false)
#section Scripts {
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
}
_PartialFooter (the partial view)
#model servicemadsen.Models.CallMe
#Html.AntiForgeryToken()
<div class="row">
<div id="result" class="margin-bottom-5">
<div class="col-md-6">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control", #placeholder = "Navn" } })
</div>
<div class="col-md-6">
#Html.EditorFor(model => model.Phone, new { htmlAttributes = new { #class = "form-control", #placeholder = "Telefon" } })
</div>
<div class="col-md-12">
#Html.TextAreaFor(model => model.CallMeMessage, new { #class = "form-control", #placeholder = "Besked", #cols = 80, #rows = 7 })
</div>
<div class="col-md-12">
#Html.ValidationMessageFor(model => model.Name, string.Empty, new { #class = "field-validation-error" })
#Html.ValidationMessageFor(model => model.Phone, string.Empty, new { #class = "field-validation-error" })
#Html.ValidationMessageFor(model => model.CallMeMessage, string.Empty, new { #class = "field-validation-error" })
</div>
</div>
</div>
Hope someone could help, its probaly some dummy thing that I need
have you installed the microsoft jquery unobstrusive ajax? if not try with that. i do some tests with your code and works.
EDIT : i also change some code for the tests
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Call(CallMe callMe)
{
if (ModelState.IsValid)
{
ModelState.Clear();
callMe.CallMeMessage = callMe.CallMeMessage + " i was on the server";
}
return PartialView("_PartialFooter", callMe);
}
and
#using (Ajax.BeginForm("Call", "Home", new AjaxOptions { UpdateTargetId = "result", InsertionMode = InsertionMode.Replace}))
{
<div id="result" class="margin-bottom-5">
#Html.Action("Call", "Home")
</div>
<button class="btn btn-common-small margin-bottom-10 pull-right" type="submit">Send</button>
}
so you can see the changes.

Ajax BeginForm POST using MVC and Razor

I keep getting a 404 and searching all over SO and cannot target the issue here. The form is the result of a render action and appears on the home page (home controller). However, I want it to post a different controller action and it keeps giving me a 404. I have included all the correct script for unobtrusive javascript as well as the necessary web.config settings and I'm unable to come across a similar problem from my research.
This is the partial with the form that is being rendered:
#model AFS.Models.SearchLocationModel
<div class="site-search-module">
<div class="site-search-module-inside">
#using (Ajax.BeginForm("SearchCare", "LevelOfCare", null, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "searchDiv" }, new { #class = "search-form", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="row">
<div class="col-md-12">
<h5>Select a category</h5>
#Html.DropDownListFor(x => x.Level, Model.LevelSelectList, new { #class = "form-control input-lg selectpicker" })
</div>
<div class="col-md-12">
<h5>Enter location</h5>
<input type="text" id="Location" name="Location" class="form-control input-lg selectpicker" placeholder="City, State OR Zip Code" required />
</div>
<div class="col-md-12"> <button type="submit" class="btn btn-primary btn-block btn-lg search"><i class="fa fa-search"></i> Search</button> </div>
</div>
}
</div>
The controller action is:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SearchCare(SearchLocationModel model)
{
if (ModelState.IsValid)
{
SearchLocationModel geocodeModel = Geocode(new SearchLocationModel() { Level = model.Level, Location = model.Location });
if (geocodeModel.Status == "OK")
{
Session["level"] = model.Level;
return RedirectToRoute("LevelCity", new { level = model.Level, state = geocodeModel.State, city = geocodeModel.City, latitude = geocodeModel.Latitude, longitude = geocodeModel.Longitude });
}
else
{
ModelState.AddModelError(string.Empty, "Please enter City, State OR Zip Code.");
return RedirectToAction("SearchWidget", "Home");
}
}
else
{
return RedirectToAction("SearchError");
}
}

MVC 5 Ajax.BeginForm only works the first time

I've been struggling for a while now with the Ajax.BeginForm.
So, what I want to achieve is:
Clicking a button that will open a Modal Popup with a Partial View inside.
When I close the Modal Popup by pressing the Save button the information will be reloaded on the target control id by call an action on the controller.
What is happening is that the first time I do this, everything seems to work as intended. However as soon as I try to add something else, it does not work anymore.
Here goes the code.
Heres the code on the view that is being loaded inside the Modal Popup
#model GEMS.Models.ViewModels.AddressVM
#{
string controllerName = ViewContext.RouteData.Values["controller"].ToString();
string actionName = ViewContext.RouteData.Values["action"].ToString();
}
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">#HTMLHelper.TranslateCRUDTitles(controllerName, actionName)</h4>
</div>
#using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, OnSuccess = "ShowSuccess", OnFailure = "ShowFailure" }))
{
#Html.AntiForgeryToken()
<div class="modal-body">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#foreach (System.Reflection.PropertyInfo prop in Model.GetDisplayProps())
{
switch (prop.Name)
{
case "NewAddressTypeName":
break;
case "AddressType":
<div class="form-group">
#Html.Label(prop.Name)
#Html.DropDownList("AddressTypeID", null, htmlAttributes: new { #class = "form-control" }).DisableIf(() => actionName == "Delete")
#Html.ValidationMessage(prop.Name, new { #class = "text-danger" })
</div>
break;
case "Country":
<div class="form-group">
#Html.Label(prop.Name)
#Html.DropDownList("CountryID", null, htmlAttributes: new { #class = "form-control" }).DisableIf(() => actionName == "Delete")
#Html.ValidationMessage(prop.Name, new { #class = "text-danger" })
</div>
break;
case "IsDefault":
<div class="form-group">
<label class="checkbox-inline">
#Html.Editor(prop.Name, new { htmlAttributes = new { #class = "grey" } }).DisableIf(() => actionName == "Delete")
#Html.Label(prop.Name)
</label>
#Html.ValidationMessage(prop.Name, new { #class = "text-danger" })
</div>
break;
case "SameAsID":
if (ViewBag.SameAsID != null)
{
<div class="form-group">
#Html.Label(prop.Name)
#Html.DropDownList(prop.Name, null, htmlAttributes: new { #class = "form-control" }).DisableIf(() => actionName == "Delete")
#Html.ValidationMessage(prop.Name, new { #class = "text-danger" })
</div>
}
break;
default:
<div class="form-group">
#Html.Label(prop.Name)
#Html.Editor(prop.Name, new { htmlAttributes = new { #class = "form-control" } }).DisableIf(() => actionName == "Delete")
#Html.ValidationMessage(prop.Name, new { #class = "text-danger" })
</div>
break;
}
}
#foreach (System.Reflection.PropertyInfo prop in Model.GetHiddenProps())
{
<input id="#prop.Name" name="#prop.Name" type="hidden" value="#Model.GetPropValue(prop.Name)">
}
</div>
<div class="modal-footer">
#if (actionName == "Delete")
{
<p>
#Resources.ConfirmAddressDelete
</p>
}
<button class="btn btn-yellow" type="button" data-dismiss="modal">
#Resources.Cancel <i class="fa fa-arrow-circle-left"></i>
</button>
#switch (actionName)
{
case "Create":
case "Edit":
<button class="btn btn-success" type="submit" value="Save">
#Resources.Save <i class="fa fa-save"></i>
</button>
break;
case "Delete":
<button class="btn btn-red" type="submit" value="Delete">
#Resources.Delete <i class="fa fa-times"></i>
</button>
break;
}
</div>
}
Here's the controller relevant actions:
public ActionResult Index(List<AddressVM> addressVMList)
{
addressVMList = addressVMList ?? (List<AddressVM>)TempData["AddressVMList"];
TempData["AddressVMList"] = addressVMList;
TempData.Keep("AddressVMList");
return PartialView("_Index", addressVMList);
}
public ActionResult Create()
{
TempData.Keep("AddressVMList");
ViewBag.AddressTypeID = new SelectList(AddressType.GetList(), "ID", "Name");
ViewBag.CountryID = new SelectList(Country.GetList(), "ID", "NiceName");
List<AddressVM> addressVMList = (List<AddressVM>)TempData["AddressVMList"];
return PartialView("_CreateEditDelete", new AddressVM());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(AddressVM addressVM)
{
if (ModelState.IsValid)
{
//Create a fake ID in order to be able to edit and manipulate the address before it is actually saved
List<AddressVM> addressVMList = (List<AddressVM>)TempData["AddressVMList"];
addressVM.Id = (addressVMList.Count + 1) * -1;
addressVMList.Add(addressVM);
if (addressVM.IsDefault) ListedPropVM.SetDefault(addressVMList.Cast<ListedPropVM>().ToList(), addressVM.Id);
TempData.Keep("AddressVMList");
string url = Url.Action("Index", "Addresses", null);
return Json(new { success = true, url = url, method = "replaceTargetAddresses" });
}
// return PartialView("_CreateEditDelete", addressVM);
return RedirectToAction("Create");
}
And finally the script that is run when OnSuccess:
function ShowSuccess(data) {
if (data.success) {
$('#defaultModal').modal('hide');
$('#' + data.method).load(data.url);
}
}
function ShowFailure(data) {
alert('Problem occured');
}
Thanks in advance for your help and time.
Well I solved the problem by adding the following to the script on the partial view:
<script type="text/javascript">
**$(document).ready(function () {
$.ajaxSetup({ cache: false });
});**
function ShowSuccess(data) {
if (data.success) {
$('#defaultModal').modal('hide');
$('#' + data.method).load(data.url);
}
}
function ShowFailure(data) {
$('#defaultModalContent').html(result);
}
</script>
Hope this helps someone else.

Resources