With ASP.NET MVC3 I'm using Jquery/Ajax to post data from a form to a function in my controller. The problem I am having is that when I put this code into my Index view it works fine, but when I put the same code into my CreatePost view I doesn't work. I can tell its working or not based on the alert and by setting a break point on the funciton in the controller.
My Controller is called BlogController and this is what the function looks like: (its a dummy function for now)
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult CreateEntry(string title, string body)
{
return Json(false);
}
The code in my view looks like this:
<script type="text/javascript">
$(function () {
$(".error").hide();
});
function SubmitEntryPostForm() {
var blogEntry = {
'title': $('#EntryTitle').val(),
'body': $('#EntryBody').val()
};
$.ajax({
type: "POST",
url: "blog/CreateEntry",
data: blogEntry,
success: function () {
alert("it worked");
}
});
return false;
}
function ValidateCreateEntry() {
$(".error").hide();
var title = $("#EntryTitle").val();
if (title == "") {
$("#title_error").show();
$("#EntryTitle").focus();
return false;
}
var body = $("#EntryBody").val();
if (body == "") {
$("#body_error").show();
$("#BodyTitle").focus();
return false;
}
return SubmitEntryPostForm();
}
<div id="CreateEntry">
<form action="">
<fieldset>
<label for="title" id="title_label">Title</label>
<input type="text" name="title" id="EntryTitle" size="30" />
<label class="error" for="title" id="title_error">This field is required.</label>
<br />
<label for="body" id="body_label">Content</label>
<input type="text" name="body" id="EntryBody" size="30" />
<label class="error" for="boby" id="body_error">This field is required.</label>
<br />
<input type="submit" name="submit" class="button" id="CreateEntryButton" value="Send" onclick="return ValidateCreateEntry();" />
</fieldset>
</form>
CreatePostlook like?