Ajax.BeginForm OnSuccess, onBegin , OnFailure not firing - javascript

No matter what I try none of javascript methods is not firing/working.
[HttpPost]
public JsonResult Errors (string name, string email)
{
//send email
return new JsonResult()
{
Data = new { result = "success" },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
Partial View
#using (Ajax.BeginForm(
"Errors",
"Home",
new AjaxOptions {
HttpMethod = "POST",
OnSuccess = "onSuccess ",
OnFailure = "OnFailure",
OnBegin = "Begin()" },
new { #class = "form-horizontal", id = "error-form" }))
{
#Html.AntiForgeryToken()
<div class="form-group">
<label>Your name</label>
<input type="text" name="name" class="form-control" value="#name" />
</div>
<div class="form-group">
<label>Your e-mail</label>
<input type="text" name="email" class="form-control" value="#email" />
</div>
<button class="btn btn-success" type="submit" style="margin-bottom:4em;">Send message</button>
}
<div class="form-group" id="thankYou" style="display:none">
<label>Thank you!</label>
</div>
</div>
</div>
</div>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
function Begin() {
alert("b");
}
function onSuccess(data) {
debugger;
alert(data.result);
};
function OnFailure(data) {
debugger;
alert(data.result);
};
$(document).ready(function () {
});
</script>
All I get is a response in JSON format. See screenshot. No event is fired. Any ideas?

Ajax.BeginForm has 11 overloads... your parameters does't match any of them. I assume you want to use this overload:
BeginForm(AjaxHelper, String, String, RouteValueDictionary, AjaxOptions, IDictionary<String,Object>)
You need to add RouteValueDictionary to your parameters:
#using (Ajax.BeginForm(
"Errors", // <--action name
"Home", // <--controller
null, // <-- RouteValueDictionary
new AjaxOptions { // <-- AjaxOptions
HttpMethod = "POST",
OnSuccess = "onSuccess ",
OnFailure = "OnFailure",
OnBegin = "Begin()" },
new { // <-- htmlAttributes
#class = "form-horizontal",
id = "error-form" }))

Related

How to send client data to MVC controller for Login page?And save to database?

Login.cshtml
<script type="text/javascript">
function data() {
var n = document.getElementById("username").value;
var m = document.getElementById("password").value;
?
</script>
<button type="submit"class="btn-login" onClick="Data()">
Giriş Yap </button>
Account Controller
DBEntities dB = new DBEntities();
[HttpPost] (username) (password)
public ActionResult Login(string KullaniciAdi,string Sifre)
{
// Session[KullaniciAdi] = dB.Profil.Where(x => x.KullaniciAdi == KullaniciAdi && x.Sifre == Sifre).FirstOrDefault();
var session = (from p in dB.Profil
where p.KullaniciAdi == KullaniciAdi
select p).FirstOrDefault();
return View();
}
My OOP homework is this website and i want to create a login with sending password and username to controller and compare submitted data and the data in the database .Please help :)
You can send client data by using ajax request,
this is your inputs
<input id="username" type="text" />
<input id="password" type="password" />
<input id="loginbutton" onclick="UserLogin()" type="submit" value="Submit" />
Submit button bind with UserLogin js function.
here is the js function. we are sending ajax post request here to our controller
<script type="text/javascript">
function UserLogin() {
var n = document.getElementById("username").value;
var p = document.getElementById("password").value;
var postObj = JSON.stringify({
"username": n,
"password": p
});
$.ajax({
url: "/Home/Login", // endpoint
type: "POST",
data: postObj,
contentType: "application/json; charset=utf-8",
success: function (result) {
// success
},
error: function (errorData) { onError(errorData); }
});
}
</script>
And your controller should be like, you can implement login logic inside of the method.
[HttpPost]
public ActionResult Login(string username, string password)
{
// use your code loged in
return Json(true, JsonRequestBehavior.AllowGet);
}
First You Create a Class :
public class LoginModel
{
[Required(ErrorMessage = "User Name can not be empty!")]
public string LOGINID { get; set; }
[Required(ErrorMessage = "Password can not be empty!")]
public string LOGINPW { get; set; }
}
Then Your Controller Action Method do this:
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(LoginModel model)
{
//Here check the Login Id and Password
return View();
}
Now in view Write this. Now when you click the submit button a post call go to the Login Controller with given LOGINID and LOGINPW :
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<!-- login screen -->
<form action="#">
#Html.TextBoxFor(m => m.LOGINID, htmlAttributes: new { #class = "form-control", placeholder = "Login ID" })
#Html.ValidationMessageFor(model => model.LOGINID, "", new { #class = "text-danger", style = "float: left" })
#Html.PasswordFor(m => m.LOGINPW, htmlAttributes: new { #class = "form-control", placeholder = "Password" })
#Html.ValidationMessageFor(model => model.LOGINPW, "", new { #class = "text-danger", style = "float: left" })
<button type="submit" class="btn btn-primary" style="background: #2e6da4; color: #FFF;">Login</button>
</form>
}
#{
var actionURL = Url.Action("Action", "Controller",
FormMethod.Post, Request.Url.Scheme)
+ Request.Url.PathAndQuery;
}
#using (Html.BeginForm("Action", "Controller", FormMethod.Post,
new { #action = actionURL }))
{
<input type="text" name="username">
<input type="text" name="password">
<button type="submit"class="btn-login"></button>
}//Then use Request.Form[0] with the id to get the user name and password in the controller action.

Return JSON with unobtrusive

I have the following code where I use Ajax.Beginform:
<div class="modal-body" style="text-align: center;">
#using (Ajax.BeginForm("LogIn", "Home", null, new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "target",
OnSuccess = "ajaxSuccess"
}, null))
{
<div class="sign_up_container">
Email:<br />
#Html.EditorFor(x => x.Login.Email, new { htmlAttributes = new { #class = "sign_up_container_input_style" } })<br/>
#Html.ValidationMessageFor(x => x.Login.Email, null, new { #class = "text-danger" })
</div>
<div class="sign_up_container">
Password:<br />
#Html.EditorFor(x => x.Login.Password, new { htmlAttributes = new { #class = "sign_up_container_input_style" } })
<br/>Forgott password?
</div>
<div class="sign_up_container">
<br />
<button type="submit" class="btn_style_3 btn">Login</button>
</div>
}
</div>
The validation works. When I enter a invalid email and hits Login, unobtrusive kicks In and says that I must enter a valid Email.
However, now I want to show a message that says that the Username or password is invalid If the user enters a invalid username or password. I have tried to do like this in my LogIn-method:
[HttpPost]
public async Task<JsonResult> Login(homeIndexViewModel model)
{
if(!ModelState.IsValid)
{
return Json(new { ModelState = "Something went wrong during login" });
}
var user = await userManager.FindAsync(model.Login.Email, model.Login.Password);
if (user != null)
{
await SignIn(user);
//return Json(new { RedirectAction = GetRedirectUrl(model.Login.ReturnUrl, user.UserId) }, JsonRequestBehavior.AllowGet);
}
return Json(new { ModelState = "Invalid email or password" }, JsonRequestBehavior.AllowGet);
}
In my Index.cshtml I'm trying to catch the json like this:
$(document).ready(function () {
function ajaxSuccess(result) {
console.log(result); //Contains error message, show It
}
});
The problem I have is that when I hit Login, I'm redirected to a white page with a json-string printed out with the message:

upload image - modal popup MVC doesn't close

I have problem. I open my website on for example on: localhost:9999/Product/Index
When I click Create icon that displays a modal popup with page /Product/Crate
I click Save.
All the records in the database correctly, but it redirects me to page /Product/Crate, and I would like to only close my modal window.
What sholuld I do?
Model:
public partial class Prod
{
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public byte[] PFile { get; set; }
}
Index View:
#using (Html.BeginForm("Create", "Products", FormMethod.Post, new {
enctype = "multipart/form-data" })){
#Html.ActionLink(" ", "Create", "Products", null, new { data_modal = "", id = "btnCreate", #class = "btn btn-small
btn-primary pull-right fa fa-cart-plus" })
#Html.ActionLink(" ", "Create", "Products", null, new { id =
"btnCreate", #class = "btn btn-small btn-primary pull-right fa
fa-cart-plus" }) }
Create View:
#using (Html.BeginForm("Create", "Products", FormMethod.Post, new { id = "form1", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="modal-body">
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ProductName, "Name", htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.EditorFor(model => model.ProductName)
#Html.ValidationMessageFor(model => model.ProductName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductDescription, "Name", htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.EditorFor(model => model.ProductDescription)
#Html.ValidationMessageFor(model => model.ProductDescription, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PFile, "File", htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.TextBoxFor(model => model.PFile, new { type = "file", name = "imageF" })
#Html.ValidationMessageFor(model => model.PFile, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal">Anuluj</button>
<input class="btn btn-primary" type="submit" value="Zapisz" />
</div>
}
Controller:
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = "PFile")] Prod pro, HttpPostedFileBase imageF)
{
if (ModelState.IsValid)
{
if (imageF != null)
{
pro.PFile= new byte[imageF.ContentLength];
imageF.InputStream.Read(pro.PFile, 0, imageF.ContentLength);
}
db.Prods.Add(pro);
db.SaveChanges();
return Json(new { success = true });
}
return PartialView("Create", pro);
}
modalform.js
$(function () {
$.ajaxSetup({ cache: false });
$("a[data-modal]").on("click", function (e) {
// hide dropdown if any
$(e.target).closest('.btn-group').children('.dropdown-toggle').dropdown('toggle');
$('#myModalContent').load(this.href, function () {
$('#myModal').modal({
/*backdrop: 'static',*/
keyboard: true
}, 'show');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form1', dialog).submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $('#file').serialize(),
contentType: 'multipart/form-data',
success: function (result) {
if (result.success) {
$('#myModal').modal('hide');
//Refresh
location.reload();
} else {
$('#myModalContent').html(result);
bindForm();
}
}
});
return false;
}); }
Please help to solve this.

ASP.NET MVC jQuery JSON result redirecting URL

Using MVC/Json/Jquery.
Using form to create a new "group".
Form is on ~Group/Manage, posting form to ~Group/Create
Whilst working on this, returning Json result was working fine, handling in Jquery, no URL redirection.
Now, everytime I run it, it redirects me to ~Group/Create and displays the Json result.
Controller Group/Create
[HttpPost]
public ActionResult Create([Bind(Include="name,description")] GroupModel groupmodel)
{
...
return Json(new { success = true, message = groupmodel.name }, JsonRequestBehavior.AllowGet);
}
Form
<form id="frm_createGroup" action="/Groups/Create" method="post">
<h2>Create Group</h2>
<div class="form-group">
#Html.LabelFor(model => model.name, new { #for = "name" })
#Html.TextBoxFor(model => model.name, new { #class = "form-control", #placeholder = "Group Name" })
#Html.ValidationMessageFor(model => model.name)
</div>
<div class="form-group">
#Html.LabelFor(model => model.description, new { #for = "description" })
#Html.TextBoxFor(model => model.description, new { #class = "form-control", #placeholder = "Group Description" })
#Html.ValidationMessageFor(model => model.description)
</div>
<span id="createGroupMessage"></span>
<button type="submit" class="btn btn-primary pull-right">Create</button>
</form>
Jquery to handle form
$(document).ready(function (){
$('#navGroups').makeActiveMenuItem();
var options = {
success: groupCreateSubmitted
,error: groupCreateError
}
$('#frm_createGroup').ajaxForm(options);
});
function groupCreateSubmitted(responseText, statusText, xhr, $form) {
if (responseText.success)
{
$('#createGroupMessage').html = "Group Created";
}
else
{
$('#createGroupMessage').html = responseText.message;
}
}
To be clear, I don't want URL redirection, I just want the Jquery to catch the return (it was before, have no idea why its changed...)
Thanks!
removed
,error: groupCreateError
working now...form bind was failing.

Validation in Partial view inside popup

I'm working in MVC and i have one scenario as follows:
I have a view called ManageResource where i il show the available resource's in grid and a button to add new resource. if i click on the add new resource button a popup il open with the partialview inside it, i have to display the validation result in popup itself when i click save with out entering any values and when i enter the required fields the values should be populated in the grid and the popup should be closed.`
"iam not getting validation result in popup, but can able to save data's"
following is my code:
Model-tblUser
public partial class tblUser
{
public int UID { get; set; }
[Required]
public int EmpID { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public decimal Salary { get; set; }
}
View-ManageResource
function Create() {
BootstrapDialog.show({
title: "Add Resource",
message: $('<div id="CreatePopup"></div>').load('#Url.Action("Create", "Resource")')
});
return false;
}
<input type="button" id="AddNewCompany" onclick="Create()" class="push_button blue btn_width" value="Add New Resource" />
partial view- Create
function SaveResource() {
var obj = [];
var EmpID = $('#EmpID').val();
var FirstName = $('#FirstName').val();
var LastName = $('#LastName').val();
var Salary = $('#Salary').val();
if ($("#IsActive").attr('checked', true)) {
var IsActive = 1;
}
else {
var IsActive = 0
}
var newrecord = {
"EmpID": EmpID, "FirstName": FirstName, "LastName": LastName, "Salary": Salary,
};
var senddata = JSON.stringify(newrecord);
jQuery.ajax({
type: "POST",
url: '#Url.Action("Create", "Resource")',
data: JSON.stringify({ "data": senddata }),
datatype: 'json',
contentType: "application/json; charset=utf-8",
success: function (result) {
if (result == true) {
window.location.href = '#Url.Action("ManageResource", "Resource")';
} else {
$("#CreatePopup").html(result);
}
}
});
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(false)
<div class="form-group">
#Html.LabelFor(model => model.EmpID, "Employee ID", new { #class = "control-label col-md-1 col-md-3" })
<div class="col-md-6">
#Html.EditorFor(model => model.EmpID)
#Html.ValidationMessageFor(model => model.EmpID)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FirstName,"First Name", new { #class = "control-label col-md-1 col-md-3" })
<div class="col-md-6">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName,"Last Name", new { #class = "control-label col-md-1 col-md-3" })
<div class="col-md-6">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-5 col-md-10">
<input type="button" id="CreateResource" onclick="SaveResource()" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
Resource Controller
public PartialViewResult Create(string data)
{
JObject o = JObject.Parse(data);//parsing the json data
tblUser tbluser = new tblUser(); //creating instance for model tblUser
if ((string)o["EmpID"] != "" && (string)o["FirstName"] != "")// if all the required fields are present then add to db
{
db.tblUsers.Add(tbluser);//assign values here
tbluser.EmpID = (int)o["EmpID"];
tbluser.FirstName = (string)o["FirstName"];
tbluser.FirstName = (string)o["FirstName"];
tbluser.LastName = (string)o["LastName"];
tbluser.EmailID = (string)o["EmailID"];
tbluser.Password = (string)o["Password"];
tbluser.RoleID = (int)o["RoleID"];
tbluser.DeptID = (int)o["DeptID"];
tbluser.DesignationID = (int)o["DesignationID"];
tbluser.Salary = (int)o["Salary"];
tbluser.IsActive = (bool)o["IsActive"];
tbluser.CreatedBy = 121;
tbluser.CreatedDate = System.DateTime.Now;
tbluser.UpdatedBy = 121;
tbluser.UpdatedDate = System.DateTime.Now;
db.SaveChanges();
return RedirectToAction("ManageResource");//return to main view when saved
}
else
{
//return with validation summary to partialview popup
return PartialView(tbluser);
}
}
When you load a form using AJAX you need to tell jQuery unobtrusive validation to add the validation data- properties to the form elements. You need to add: $.validator.unobtrusive.parse('#YourFormSelector');
after the .load is completed.
function Create() {
BootstrapDialog.show({
title: "Add Resource",
message: $('<div id="CreatePopup"></div>').load('#Url.Action("Create","Resource")'
, function() {$.validator.unobtrusive.parse('#YourFormSelector');})
});
return false;
}

Categories