i want run JavaScript/jQuery from view but didn't show me anything. my code work and data is recorded in database but don't know why JavaScript/jQuery didn't work
my code are:
Action Code:
[HttpPost]
public ActionResult Register(User user)
{
UserRepository blUser = new UserRepository();
if (ModelState.IsValid)
{
if (blUser.Add(user))
{
return Json(new JsonData() { Success = true });// return {"Success":true}
}
else
{
return Json(new JsonData() { Success = false }); // return {"Success":false}
}
}
else
{
return Json(new JsonData() { Success = false }); // return {"Success":false}
}
}
and view code:
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script>
$(document).ready(function (e) {
e.preventDefault();
$("#reg-btn").click(function () {
$.ajax({
type: "Post",
url: "/Home/Register",
data: null,
dataTpe: "Json",
success: function (result) {
if (result.Success == true) {
alert("success");
}
},
error: function () {
alert("error");
}
});
});
});
</script>}
nothing happen when submit button pressed just data record in database ... just in new page show me " {"Success":true} " if i removed this line code in view:
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
still didn't work if i changed return in controller
return JavaScript("alert('success')"); // again show string "alert('success')" in new page if above line code removed
and partial view too...
which JavaScript reference file added to my project? default created by visual studio 2015 / MVC 4 + jquery.unobtrusive-ajax.min.js
ty
Your e.preventDefault()
is in wrong place and is likely throwing error in dev tools console
Change
$(document).ready(function (e) {
e.preventDefault();
$("#reg-btn").click(function () {
....
To
$(document).ready(function () {
$("#reg-btn").click(function () {
e.preventDefault();
....
I found the solution to my problem. just in Ajax.BeginForm
method, i added OnSuccess
and OnFailure
properties to AjaxOptions
... and defined 2 functions for both in script section
@using (Ajax.BeginForm("Register",new AjaxOptions {
OnSuccess = "OnSuccess",
OnFailure = "OnFailure"
}))
{
and in script section
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script type="text/javascript">
function OnSuccess(response) {
alert("done");
}
function OnFailure(response) {
alert("error");
}
</script>
I hope this answer will help others in the future
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.