I am posting a form using Ajax.BeginForm
due to the fact that I have some methods running in my controller's POST
method which checks to see whether the proposed record is valid in terms of what already exists in the table.
// POST: Electricity
[HttpPost]
public ActionResult CreateSite(ElectricitySiteViewModel newElectricitySiteViewModel)
{
var dbElectricitySite = AutoMapper.Mapper.Map<ElectricitySite>(newElectricitySiteViewModel);
if (_service.DoesSiteExist(newElectricitySiteViewModel.SiteNumber)) // site already exists, check balance of split
{
if (_service.DoesSiteBalance(newElectricitySiteViewModel.SiteNumber, newElectricitySiteViewModel.SplitPercentage)) // if it balances, create and redirect
{
_service.CreateElectricitySite(dbElectricitySite);
return JavaScript("window.location = 'http://www.google.co.uk'");
}
else // doesnt balance, return to create view
{
ViewBag.DoesNotBalance = true;
return View();
}
}
else //site does not exist, create it and redirect
{
_service.CreateElectricitySite(dbElectricitySite);
return JavaScript("window.location = 'http://www.google.co.uk'");
}
}
I am using the ViewBag
as a flag to show the user that the split they have attempted contradicts with the site record already held, so I can show an additional message without having to do a post back.
What's happening however is when the POST is valid, and the record created, I'm trying to force the browser to postback to google by doing:
return JavaScript("window.location = 'http://www.google.co.uk'");
Which I have used successfully before, but this time I'm seeing this:
EDIT
Following @JamieD77 's comments, I instead added an OnSuccess parameter to my Ajax.BeginForm to display a message as a test:
@using(Ajax.BeginForm(new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "updatearea", OnSuccess = "Test" }))
and added a script to my page:
@section DialogScripts{
<script type="text/javascript">
function Test(data) {
switch (data.result) {
case 1:
alert(data.result)
break;
case 0:
alert(data.result)
break;
case -1:
alert(data.result)
break;
default:
alert(data.message);
}
}
</script>
}
And had my controller return:
return Json(new { result = 0, message = "Record created." });
But I get the same thing, the JSON is just output to the browser, much like the screen shot from before, but this time its JSON.
What is going on here, am I missing a library perhaps?