How to submit AJAX Form using radio button change event? - c#

I have a AJAX form & I want to submit it on radio button change event.
AJAX Form:
#using (Ajax.BeginForm("Vote", "Rate", null ,
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET",
OnFailure = "searchFailed",
LoadingElementId = "ajax-loader",
UpdateTargetId = "searchresults",
},new { id = "voteForm" }))
{
<input type="radio" name="Stars" value="1">
<input type="radio" name="Stars" value="2">
<input type="radio" name="Stars" value="3">
}
I uses following code but it does not work.
$("#voteForm").ajaxSubmit({ url: '/Vote/Vote', type: 'get' });

Try this:
<script type="text/javascript">
$(function () {
$("input[name='Stars']").change(function() {
$("#voteForm").ajaxSubmit({ url: '/Vote/Vote', type: 'get' });
});
});
</script>

#Babul Mirdha Ajax.BeginForm is a mechanism that works fine, but customize specific submit behaviors very different from the standard can generate big headache. I think now you know that.
Every time I (and many other developers will say it too) need to develop some custom behavior I use the basic Jquery. Like this:
In your controller:
public JsonResult Vote(YourModel model)
{
// do something:
// model.Stars
return Json(new { message = "Success" }, JsonRequestBehavior.AllowGet);
}
Your model:
public class YourModel
{
// ...
public int Stars { get; set; }
}
And your view:
<script type="text/javascript">
$(function () {
$("#voteForm input[name=Stars]").change(function () {
$.ajax({
url: '/Home/Vote',
type: 'GET',
data: $("form#voteForm").serialize(),
dataType: 'json',
success: function (data) {
alert(data.message);
},
error: function (jq, message) {
alert(message);
}
});
});
});
</script>
<form id="voteForm" action="#Url.Action("Vote")">
<input type="radio" name="Stars" value="1" checked="checked"/>
<input type="radio" name="Stars" value="2" />
<input type="radio" name="Stars" value="3" />
<input type="text" name="Tbx" />
</form>
This way you have full control over behavior.

Related

FormData not binding values to controller

I have an Asp.net core application in which I have a form. When I click on the submit button I am using jquery ajax post to submit the form. I am facing 2 problems here,
When I press the submit button, the client side validations are not happening and the form is being submitted.
I have a Break point in the SendEmail Method, and for some reason the FormData binds all null values to the object. Please help.
Here is my form
<form name="ajax-form" id="formPostComment" enctype="multipart/form-data" method="post">
<div class="col-sm-6 contact-form-item wow zoomIn">
<input name="name" id="name" type="text" placeholder="Your Name: *" required/>
<span class="error" id="err-name">please enter name</span>
</div>
<div class="col-sm-6 contact-form-item wow zoomIn">
<input name="email" id="email" type="text" placeholder="E-Mail: *" required/>
<span class="error" id="err-email">please enter e-mail</span>
<span class="error" id="err-emailvld">e-mail is not a valid format</span>
</div>
<div class="col-sm-6 contact-form-item wow zoomIn">
<label for="myfiles">Select file (If Any):</label>
<input name="attachment" id="attachment" type="file" />
</div>
<div class="col-sm-12 contact-form-item wow zoomIn">
<textarea name="message" id="message" placeholder="Your Message" required></textarea>
</div>
<div class="col-sm-12 contact-form-item">
<input class="send_message btn btn-main btn-theme wow fadeInUp" type="submit" id="submit" name="submit" data-lang="en" onclick="SendEmail();"></input>
</div>
<div class="clear"></div>
<div class="error text-align-center" id="err-form">There was a problem validating the form please check!</div>
<div class="error text-align-center" id="err-timedout">The connection to the server timed out!</div>
<div class="error" id="err-state"></div>
</form>
<script>
function SendEmail() {
var formData = new FormData();
formData.append("Name", $("#name").val());
formData.append("Email", $("#email").val());
formData.append("Attachment", $("#attachment")[0]);
formData.append("Message", $("#message").val());
alert($("#name").val());
$.ajax({
type: 'POST',
url: "/Home/SendEmail",
data: formData,
processData: false,
contentType: false,
cache: false,
success: function (response) {
alert("Done");
$('#formPostComment')[0].reset();
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
//}).done(function (data) {
// console.log(data);
// $("#ajaxwaiting").hide();
// $("#ajaxsuccess").show();
//});
event.preventDefault();
}
</script>
Here is my Controller action method.
[HttpPost]
public IActionResult SendEmail([Bind("Name,Email,Attachment,Message")] SingleEmailMessage message)
{
return Json(new { data = "DONE" });
}
The SingleEmailMessage class is as follows,
public class SingleEmailMessage
{
public string Name { get; set; }
public string Email { get; set; }
public IFormFile Attachment { get; set; }
public string Message { get; set; }
}
you might be sending two POSTs here... don't use onclick on the submit... instead use onsubmit on the form tag... ex:
<form ... onsubmit="SendEmail(); return false;"> Don't forget the "return false;" bit that replaces your event.preventDefault() call. It's also easier to pass the form's ID into your function... so
SendEmail("formPostComment")... then function SendEmail(id) {
...
thisForm = document.getElementById(id);
var formData = new FormData(thisForm);
On controller side get the file by using:
if (Request.Form.Files.Count > 0)
{
IFormFile file = Request.Form.Files[0];
}
Not sure that the file is going to bind to your model.... get it from the raw request.
The full JS function I use is this (just for reference):
//for uploads
function PostFileFormID(id, buttonid, destURL) {
$('#' + buttonid).attr('value', "Uploading...");
thisForm = document.getElementById(id);
var formData = new FormData(thisForm);
jQuery.ajax({
type: 'POST',
url: destURL,
data: formData,
processData: false,
contentType: false,
success: function (data) {
params = convertJsonToParams(data);
url = "?" + params;
setLocation(url);
},
error: function (jqXHR, textStatus, error) {
DisplaySuperError(jqXHR, textStatus, error);
}
});
}

How to handle a form that have next and previous buttons with one submit button

I have a pop up that have a questions for the user,when the user answer first question and click next the second question will appear and so on , I want to submit this form once the user answer all these question and click the last next button ,
Can i handle that with one submit button?
In the following an example to show how to make a wizard, the example is limited on two views (FirstView and SecondView), it is done with Notepad and remains to test it.
Index View
#model namespace.MyModel
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<head>
<script type="text/javascript">
$("#StartWizardButton").on("click", ShowWizard('FirstParamerValue'));
function ShowWizard(parameter) {
$.ajax({
url: '#Url.Action("FirstViewAction", "HomeController")',
type: "GET",
data:{model:JSON.Parse(#Html.Raw(Json.Encode(Model)))},
success: function (response, status, xhr) {
$('#WizardModalContainer').html(response);
$('#WizardModalDiv').modal({ backdrop: 'static', keyboard: false });
},
error: function (response) {
alert(response.responseText);
}
});
}
</script>
</head>
<body>
<button id="StartWizardButton" type="submit" data-toggle="modal">Start Wizard</button>
............
<div class="modal fade container" id="WizardModalDiv" tabindex="1" role="dialog" aria-hidden="true">
<div class="modal-dialog" id="Wizard-modal-dialog">
<div class="modal-content" id="WizardModalContent">
<div class="modal-header" id="WizardModalHeader"></div>
<div class="modal-body" id='WizardModalContainer'>
</div>
<div class="modal-footer" id="WizardModalFooter">
<button type="button" class="btn btn-default" data-dismiss="modal">Fermer</button>
<button type="button" onclick="ShowWizard(); return false;" class="btn btn-primary">Next</button>
</div>
</div>
</div>
</div>
</body>
First View
#model namespace.FirstModel
<head>
<script type="text/javascript">
$("#SecondViewWizardButton").on("click", ShowSecondView());
function ShowSecondView() {
$.ajax({
url: '#Url.Action("SecondViewAction", "HomeController")',
type: "GET",
data:{model:JSON.Parse(#Html.Raw(Json.Encode(FirstModel)))},
success: function (response, status, xhr) {
$('#WizardModalContainer').html(response);
},
error: function (response) {
alert(response.responseText);
}
});
}
</script>
</head>
<body>
<button id="SecondViewWizardButton" type="submit" data-toggle="modal">Next</button>
............
</body>
Second View
#model namespace.SecondModel
<head>
<script type="text/javascript">
$("#SecondView").on("click", ShowSecondView());
function ShowSecondView() {
$.ajax({
url: '#Url.Action("SecondViewAction", "HomeController")',
type: "GET",
data:{model:JSON.Parse(#Html.Raw(Json.Encode(SecondModel)))},
success: function (response, status, xhr) {
$('#WizardModalDiv').modal('hide');
},
error: function (response) {
alert(response.responseText);
}
});
}
</script>
</head>
<body>
<button id="SecondViewWizard" type="submit" data-toggle="modal">Next</button>
............
</body>
The Controller
public class CommandeController : Controller
{
public ActionResult Index()
{
return View("Index", MyModel);
}
public PartialViewResult FirstViewAction(MyModel model)
{
............
return PartialView("FirstView", FirstModel);
}
public PartialViewResult SecondViewAction()
{
...........
return PartialView("SecondView", SecondModel);
}
}
Cordially

Jquery form submit() to the action in the controller then returns an object to the client and not reload page

I want after I call the submit() function in jQuery. It will go to action to process the logic, then the action will return an object to the client, so the client displays it.
I tried many ways but no, please help me.
I have a form like this:
<form action="/Mycontroller/Save" id="myform" enctype="multipart/form-data" method="post">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
</form>
<button class="btn btn-success" type="button" onclick="Save()">Save</button>
I want to try Code Js:
function Save(
$("#myform").submit(function (eventData, handler) {
var resultFromAction = ???
// I would like to get the object from the action returned
});
)
Or
function Save(
var resultFromAction = $("#myform").submit();
// I would like to get the object from the action returned
)
Code action in controller:
public class MyControllerController: Controller {
[Authorize]
public ActionResult Save(FormObject formobj) {
// do something
var resultForClient = new {
phone: "098989878",
name: "john",
add: "My address"
};
return Json(resultForClient, JsonRequestBehavior.AllowGet);
}
}
Firstly you should place the <button> within the <form> and change its type to submit:
<form action="/Mycontroller/Save" id="myform" enctype="multipart/form-data" method="post">
First name:<br />
<input type="text" name="firstname" value="Mickey"><br />
Last name:<br />
<input type="text" name="lastname" value="Mouse"><br /><br />
<button class="btn btn-success" type="submit">Save</button>
</form>
You can then attach an event handler directly to the submit event of the form to send your AJAX request using jQuery's $.ajax() method:
$("#myform").submit(function(e) {
e.preventDefault(); // stop the standard form submission
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(data) {
console.log(data); // the object returned from your Action will be displayed here.
}
});
});

Ajax refreshing page in MVC

I'm using Ajax to pass some data to a Controller and save to database, and it works, the issue that is refreshing the page with every POST and I need to prevent that.
Ajax:
function AddComment(commet, auto) {
$.ajax({
type: "POST",
url: '/bff/SaveComment',
data: { id: idParte, commenta: commet, autoriza: auto },
dataType: 'json',
success: function (correct) {
$("#win1").show().kendoWindow({
width: "300px",
height: "100px",
modal: true,
title: "Added"
});
},
errror: function(inc) {
}
});
}
Controller:
[HttpPost]
public JsonResult SaveComment(int id, string commenta, string autoriza)
{
// Some logic here
return Json("");
}
Tried this way with correct.preventDefault(); but didn't work
Is there a way to do it?
EDITED:
This is my HTML:
<form role="form">
<div class="form-group">
#Html.Label("Commentario:")
<textarea id="Comment" style="resize:none;" class="form-control"></textarea>
</div>
<div class="form-group">
<input type="submit" value="Guardar" onclick="AddComment(Comment.value,'Comentario')" />
</div>
</form>
EDITED 2:
Fixed by changing type="submit" for type="button" Thanks to Hasta Pasta
i think you should put return false; after the ajax request
function AddComment(commet, auto) {
$.ajax({
type: "POST",
url: '/bff/SaveComment',
data: { id: idParte, commenta: commet, autoriza: auto },
dataType: 'json',
success: function (correct) {
$("#win1").show().kendoWindow({
width: "300px",
height: "100px",
modal: true,
title: "Added"
});
},
error: function(inc) {
}
});
return false;
}
based on you need to return false as you sayed :)
<form role="form">
<div class="form-group">
#Html.Label("Commentario:")
<textarea id="Comment" style="resize:none;" class="form-control"></textarea>
</div>
<div class="form-group">
<input type="submit" value="Guardar" onclick="return AddComment(Comment.value,'Comentario')" />
</div>
</form>

Ajax.Actionlink of type post inside Html.Beginform doens't send the value of form to controllers post method?

I have a form
<script src="#Url.Content("~/Scripts/jquery-1.8.2.min.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
#using (Html.BeginForm("Index", "Company",IsPost))
{
<div class="input-block-level">#Html.TextBoxFor(m => m.SearchString)
#Ajax.ActionLink("Submit", "Index", new{#class="btn"},new AjaxOptions {
HttpMethod = "Post",
UpdateTargetId = "partialDiv"
})
</div>
}
<div id="partialDiv"></div>
When the link that is created via Ajax.Actionlink in browser is clicked, I don't get the value of the textbox in controllers post method. Why is that? Also, should I use Ajax.BeginForm? I haven't use Ajax.BeginForm yet, any tips on how could this Html.BeginForm be transformed to Ajax.BeginForm?
Instead of Html.BeginForm you should use Ajax.BeginForm, and change the submit to the normal submit input: <input type="submit" ....
I suggest to take a look at this question: Using Ajax.BeginForm with ASP.NET MVC 3 Razor
Have you tried making the request in jQuery?
<div class="container">
#Html.TextBoxFor(m => m.Input, new { #id = "myInput"})
<input type="submit" value="Submit" class="submit"/>
</div>
#section scripts{
<script type="text/javascript">
$('.submit').on('click', function() {
var searchValue = $('#myInput').val();
$.ajax({
type: "POST",
dataType: 'json',
url: "/Home/MyMethod",
data: {data: searchValue},
success: function(data) {
console.log();
}
});
});
</script>
}
//Controller
[HttpPost]
public ActionResult MyMethod(string data)
{
//do something
}

Categories