Passing data from jQueryUI dialog form to controller - javascript

I'm new with ASP.NET/Javascript and I'm having a little trouble with the implementation of simple CRUD operations using jQueryUI dialog form. This is my code:
<button class="update" id="#Model.id">Update</button>
<div id="dialog-form" title="Update">
<form>
<fieldset>
<input type="text" name="state" id="state">
<input type="text" name="note" id="note">
<input type="submit">
</fieldset>
</form>
</div>
<script>
$(function() {
var dialog,
state = $("#state"),
note = $("#note"),
id = this.id, //??
dialog = $("#dialog-form").dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Ok": function() {
$.ajax({
type: "POST",
url: "#Url.Action("Update","Ticket")",
data: {
id: id,
state: state,
note: note
},
cache: false,
dataType: "json",
success: function(data) {
$("#dialog").dialog("close");
}
});
},
"Cancel": function() {
$(this).dialog("close");
}
}
});
$(".update").button().on("click", function() {
dialog.dialog("open");
});
});
</script>
Finally the Update action in TicketController:
public ActionResult Update(String id, String state, String note)
{
//do some stuff
}
However nothing happens and it doesn't get into the action. Any help is greatly appreciated

change your data as below you need to pass value rather than the object by using .val()
state = $("#state").val(),
note = $("#note").val(),
id = "Pass anything you wants"
data: { 'id':id,'state':state,'note':note },
Decorate your action method with [HttpPost]
[HttpPost]
public ActionResult Update(String id, String state, String note)
{
}

Related

How can I serialize a form in JavaScript asp.net

I am using some javascript to post my form but I dont want to have to submit each form field is there a way I can serlize this to an object in .net so that it will bring in all the form contents.
section Scripts {
<script>
function confirmEdit() {
swal({
title: "MIS",
text: "Case Created your Case Number is " + $("#Id").val(),
icon: "warning",
buttons: true,
dangerMode: true,
}).then((willUpdate) => {
if (willUpdate) {
$.ajax({
url: "/tests/edit/" + $("#Id").val(),
type: "POST",
data: {
Id: $("#Id").val(),
Name: $("#Name").val()
},
dataType: "html",
success: function () {
swal("Done!", "It was succesfully edited!", "success")
.then((success) => {
window.location.href = "/tests/index"
});
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error updating!", "Please try again", "error");
}
});
}
});
}
</script>
}
asp.net core will automatically bind json data using the [FromBody] attribute.
data: {
id: $("#Id").val(),
name: $("#Name").val()
},
and then in your controller
[HttpPost("/tests/edit/")]
public IActionResult Process([FromBody] MyData data){ ... }
where MyData is
public class MyData
{
public string Id {get;set;}
public string Name {get;set;}
}
section Scripts { function confirmEdit() {
swal({ title: "MIS", text: "Case Created your Case Number is " + $("#Id").val(), icon: "warning", buttons: true, dangerMode: true, }).then((willUpdate) => { if (willUpdate) {
var obj = { Id: $("#Id").val(), Name: $("#Name").val() }
$.ajax({ url: "/tests/edit/" + $("#Id").val(), type: "POST", data: JSON.Stringify(obj), dataType: "html", success: function () { swal("Done!", "It was succesfully edited!", "success") .then((success) => { window.location.href = "/tests/index" }); }, error: function (xhr, ajaxOptions, thrownError) { swal("Error updating!", "Please try again", "error"); } }); } }); } }
in c# use
public ActionResult FormPost(MyData obj)
Please refer to the following methods to submit the form data to action method:
using the serialize() method to serialize the controls within the form.
#model MVCSample.Models.OrderViewModel
<h4>OrderViewModel</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Showsummary" asp-controller="Home" method="post" class="signup-form">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="OrderId" class="control-label"></label>
<input asp-for="OrderId" class="form-control" />
<span asp-validation-for="OrderId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="OrderName" class="control-label"></label>
<input asp-for="OrderName" class="form-control" />
<span asp-validation-for="OrderName" class="text-danger"></span>
</div>
<div id="packages">
#for (int i = 0; i < Model.Packages.Count; i++)
{
<div class="form-group">
<label asp-for="#Model.Packages[i].Pid" class="control-label"></label>
<input asp-for="#Model.Packages[i].Pid" class="form-control" />
<span asp-validation-for="#Model.Packages[i].Pid" class="text-danger"></span>
<br />
<label asp-for="#Model.Packages[i].PackageTitle" class="control-label"></label>
<input asp-for="#Model.Packages[i].PackageTitle" class="form-control" />
<span asp-validation-for="#Model.Packages[i].PackageTitle" class="text-danger"></span>
</div>
}
</div>
</form>
</div>
</div>
<div>
<input type="button" id="summary" value="Summary" />
<div id="page_3">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function () {
$("#summary").click(function () {
console.log("calling summary");
event.preventDefault();
$.ajax({
type: "POST",
url: "/Home/Showsummary", //remember change the controller to your owns.
data: $("form.signup-form").serialize(),
success: function (data) {
console.log(data)
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
});
});
</script>
Code the the action method:
[HttpPost]
public PartialViewResult Showsummary(OrderViewModel model)
{
try
{
//...
return PartialView("OrderSummary", model);
}
catch
{
return PartialView("OrderSummary", model);
}
}
After clicking the button, the result like this:
As we can see that, we could get the element's value in the form and even the nested entity.
Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.
Create a JavaScript object, and post it to action method.
Change the JavaScript script as below:
$(function () {
$("#summary").click(function () {
console.log("calling summary");
event.preventDefault();
//create a object to store the entered value.
var OrderViewModel = {};
//using jquery to get the entered value.
OrderViewModel.OrderId = $("input[name='OrderId']").val();
OrderViewModel.OrderName = $("input[name='OrderName']").val();
var packages = [];
//var count = $("#packages>.form-group").length; //you could use it to check the package count
$("#packages>.form-group").each(function (index, item) {
var package = {}
package.Pid = $(item).find("input[name='Packages[" + index + "].Pid']").val();
package.PackageTitle = $(item).find("input[name='Packages[" + index + "].PackageTitle']").val();
packages.push(package);
});
//add the nested entity
OrderViewModel.Packages = packages;
$.ajax({
type: "POST",
url: "/Home/Showsummary", //remember change the controller to your owns.
data: OrderViewModel,
success: function (data) {
console.log(data)
$('#page_3').html(data);
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
});
});
By using the above code, I could also get the submit entity, you could refer to it.

Call Action Method on button click ASP.NET MVC

I am trying to get user input in button click.
When user insert number and press Check, it needs to return xml data type.
So in my controller I create function which will return a data for passing ID
[ResponseType(typeof(AKONTA))]
public IHttpActionResult GetAKONTA(string id)
{
AKONTA aKONTA = db.AKONTAS.Find(id);
if (aKONTA == null)
{
return BadRequest("Ne postoji A_KONTO pod tim rednim brojem");
}
return Ok(aKONTA);
}
And In my View I have following
<br /><br />
<form>
<div class="form-group">
<label>A_KONTO</label>
<input type="text" class="form-control" aria-describedby="AKONTO BROJ" placeholder="Unesite broj AKONOTO">
</div>
<div class="form-group">
<a asp-action="Index" class="btn btn-primary" id="aKonto" action="#Url.Action("GetAKONTA", "Akontas")">Provjeri</a>
</div>
</form>
And I want to create in btn click when user pass ID it needs to return XML data format.
SO far I create a JS function, but I don't know JavaScript and don't know the logic how to pass Controller Action Result to JS.
<script>
$(document).ready(function () {
$('#aKonto').click(function () {
document.getElementById("aKonto").onclick = function () {GetAKONTA()};;
});
});
</script>
If someone can help me I would be very thankful.
Cheers !
UPDATE
function aKontoSubmit() {
$.ajax({
type: "GET",
url: 'api/Akontas',
//data: { id: id },
dataType: "xml",
success: function (result) {
// action to do after form submit
},
error: function () {
alert("Ne postoji AKONTO pod tim rednim brojem");
}
});
}
**routeConfig**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace AkontasWebApi
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
Add Reference of Jquery, to try the ajax call method.
function aKontoSubmit() {
$.ajax({
type: "POST",
url: '/Akontas/GetAKONTA',
data: $('form').serialize(),
dataType: "json",
success: function (result) {
// action to do after form submit
},
error: function () {
alert("Error while inserting data");
}
});
}
Change you Link Code as Below
<a asp-action="Index" class="btn btn-primary" id="aKonto" onClick='return aKontoSubmit() '>Provjeri</a>
Or Else You Can try if you are using ASP.Net MVC Core Development
<form asp-action="GetAKONTA" asp-controller="Akontas" method="post">
<div class="form-group">
<label>A_KONTO</label>
<input type="text" class="form-control" aria-describedby="AKONTO BROJ" placeholder="Unesite broj AKONOTO">
</div>
<div class="form-group">
<input class="btn btn-primary" id="aKonto" type = "submit" value = "Provjeri" />
</div>
</form>
After a couple hours of debugging and searching I found that I forget to put
window.location.href = "http://localhost:57285/api/Akontas/" + $('#AkontasId').val();
This is location where should redirect if item exsist in database
And URL call need to be modified as well
URL: "/api/Akontas/GetAKONTA",
function aKontoSubmit() {
$.ajax({
type: "GET",
URL: "/api/Akontas/GetAKONTA",
data: { id: $('#AkontasId').val() },
contentType: "data/xml; charset=utf-8",
success: function (result) {
window.location.href = "http://localhost:57285/api/Akontas/" + $('#AkontasId').val();
},
error: function () {
alert("Ne postoji AKONTO pod tim rednim brojem");
}
});
}

Jquery-Ui Dialog form for each button in a dynamic table

I am generating an HTML table with a button for each row which have to open a Jquery ui dialog form.
//The table
<table class="table table-reporting table-condensed table-striped" id="tableoperator">
<tbody>
#for (int h = 0; h < Model.ToList().Count; h++)
{
<tr>
<td class="hidden-phone hidden-tablet">
<button class="update" id="#Model.ElementAt(h).id">Update</button>
</td>
</tr>
}
</tbody>
</table>
//The dialog form
<div id="dialog-form" title="Update Ticket" >
<form>
<fieldset>
<label for="state">State</label>
<input type="text" name="state" id="state" class="text ui-widget-content ui-corner-all">
<label for="note">Note</label>
<input type="text" name="note" id="note" class="text ui-widget-content ui-corner-all">
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
<script>
$(function () {
var dialog,
state = $("#state").val(),
note = $("#note").val(),
id = id of button Update??
dialog = $("#dialog-form").dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Ok": function () {
$.ajax({
type: "POST",
url: "#Url.Action("Update","Ticket")",
data: { 'id': id, 'state': state, 'note': note },
cache: false,
dataType: "json",
success: function (data) {
$(this).dialog("close");
}
});
},
"Cancel": function () {
$(this).dialog("close");
}}
});
$(".update").button().on("click", function () {
dialog.dialog("open");
});
});
</script>
But the problem is that in the action Update of TicketController the parameters state and node are empty. What can I do? And How can I set id = id of button Update?
//////// Edit: this is the correct code (as suggested by #Igor)
<script>
$(function () {
var state = $("#state").val(),
note = $("#note").val(),
dialog = $("#dialog-form").dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Ok": function () {
$.ajax({
type: "POST",
url: "#Url.Action("Update","Ticket")",
data: { 'id': $(this).data("idt"), 'state': $("#note").val(), 'note': $("#note").val() },
cache: false,
dataType: "json",
success: function (data) {
$(this).dialog("close");
}
});
},
"Cancel": function () {
$(this).dialog("close");
}}
});
$(".update").button().on("click", function () {
dialog.data("idt", this.id);
dialog.dialog("open");
});
});
</script>
1.Store id of the clicked button in the dialog data property before you open the dialog.
2.Retrieve values to be sent inside the "Ok" click.
"Ok": function () {
var id = dialog.data("buttonid");
var state = $("#state").val();
var note = $("#note").val();
$.ajax({
...
$(".update").button().on("click", function () {
dialog.data("buttonid", this.id);
dialog.dialog("open");
});

Buttons within dialog boxes and how to get the respective button value on form submit

I have a razor view which has a form. Within the form there is a button called upload. The upload button posts to an action method which is working fine.
I want to add a modal box confirmation which would appear when they hit upload button, now within the modal box I want to have two buttons. One would say "Normal Parsing" and the other would say "Buffer Parsing". Once they press either button within the dialog box, the form will submit to the action method and within the action method I want to see which dialog button they pressed, either "Normal Parsing" or "Buffer Parsing".
This is what I have so far for the dialog box, I just need to see how will the controller get the value of the button pressed. Thanks guys!!
function getParsingRoute(){
var buttonPressed;
.dialog({
modal: true,
width: 600,
title: 'Parsing Values Confirmation',
buttons: {
"Normal Parsing": function () {
buttonPressed = "Normal";
},
"Buffer Parsing": function () {
buttonPressed = "Buffer
}
}
})
}
#using (Html.BeginForm("Create", "RunLogEntry", FormMethod.Post, new { id = "form", enctype = "multipart/form-data" }))
{
<button name="submit" class="art-button" type="submit" value="Upload" onclick="getParsingRoute()" style="width: 100px">Upload</button>
}
Solution inpired by #Barmar comment:
function getParsingRoute(e){
e.stopPropagation();
.dialog({
modal: true,
width: 600,
title: 'Parsing Values Confirmation',
buttons: {
"Normal Parsing": function () {
$("#hiddenInput").val("Normal Parsing");
},
"Buffer Parsing": function () {
$("#hiddenInput").val("Buffer Parsing");
}
}
})
$("#form").submit();
}
#using (Html.BeginForm("Create", "RunLogEntry", FormMethod.Post, new { id = "form", enctype = "multipart/form-data" }))
{
<input name="inputName" type="hidden" id="hiddenInput" value="" />
<button name="submit" class="art-button" type="submit" value="Upload" onclick="getParsingRoute()" style="width: 100px">Upload</button>
}
Try something that:
function getParsingRoute(){
var buttonPressed;
.dialog({
modal: true,
width: 600,
title: 'Parsing Values Confirmation',
buttons: {
"Normal Parsing": function () {
$.ajax({
url: "http://example.com",
type: "POST",
data: contactForm.serialize() + "&buttonPresed=Normal Parsing"
}).done(function (data) {
//done
})
},
"Buffer Parsing": function () {
$.ajax({
url: "http://example.com",
type: "POST",
data: contactForm.serialize() + "&buttonPresed=Buffer Parsing"
}).done(function (data) {
//done
})
}
}
})
}
This code only show you way how you can do it.

Submit checkbox state without a submit button

I have a view with a few checkboxes that can be selected or unselected. I'd like to always register any change in a checkbox, without the use of a submit button (the user could forget to do it, and it would waste time).
So, is there a way to handle this inside the view? Up to now, I've only used the controller to do that job.
So, a piece of code :
#ModelType MvcApplication.OpportuniteDetails
#Code
ViewData("Title")="Details"
#End Code
<script type="text/javascript">
$(function () {
$(':checkbox').change(function() {
$.ajax({
url: '#Url.Action("update")',
type: 'POST',
data: { isChecked: $(this).is(':checked') },
success: function (result) { }
});
});
});
</script>
[... Some code here...]
#Html.Raw("Mail sent?") #Html.CheckBox(Model.Opportunite.Mail)
<input type="checkbox" name="mail" id="mail" onclick="test()" />
You could use AJAX:
$(function() {
$(':checkbox').change(function() {
var form = $(this).closest('form');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(result) {
}
});
});
});
In this example we subscribe to the change event of each checkbox. When this event is trigerred we look for the containing form and send its contents to the server using an AJAX request.
And if you only wanted to submit the current checkbox state to the server and not the entire form:
$(function() {
$(':checkbox').change(function() {
$.ajax({
url: '#Url.Action("SomeAction")',
type: 'POST',
data: { isChecked: $(this).is(':checked') },
success: function(result) {
}
});
});
});
where you could have a controller action which will do the necessary processing:
[HttpPost]
public ActionResult SomeAction(bool isChecked)
{
...
}
If you don't need or want AJAX and just want to submit the form, this
$(':checkbox').change(function() {
var form = $(this).closest('form');
form.get( 0 ).submit();
});
would do it.

Categories