Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

publicclassMyData
{
   publicstring Id {get;set;}
   publicstring Name {get;set;}
}

Solution 2:

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)

Solution 3:

Please refer to the following methods to submit the form data to action method:

  1. using the serialize() method to serialize the controls within the form.

    @model MVCSample.Models.OrderViewModel
    
     <h4>OrderViewModel</h4><hr /><divclass="row"><divclass="col-md-4"><formasp-action="Showsummary"asp-controller="Home"method="post"class="signup-form"><divasp-validation-summary="ModelOnly"class="text-danger"></div><divclass="form-group"><labelasp-for="OrderId"class="control-label"></label><inputasp-for="OrderId"class="form-control" /><spanasp-validation-for="OrderId"class="text-danger"></span></div><divclass="form-group"><labelasp-for="OrderName"class="control-label"></label><inputasp-for="OrderName"class="form-control" /><spanasp-validation-for="OrderName"class="text-danger"></span></div><divid="packages">
    
                     @for (int i = 0; i < Model.Packages.Count; i++)
                     {
                     <divclass="form-group"><labelasp-for="@Model.Packages[i].Pid"class="control-label"></label><inputasp-for="@Model.Packages[i].Pid"class="form-control" /><spanasp-validation-for="@Model.Packages[i].Pid"class="text-danger"></span><br /><labelasp-for="@Model.Packages[i].PackageTitle"class="control-label"></label><inputasp-for="@Model.Packages[i].PackageTitle"class="form-control" /><spanasp-validation-for="@Model.Packages[i].PackageTitle"class="text-danger"></span></div> 
                     }
    
                 </div></form></div></div><div><inputtype="button"id="summary"value="Summary" /><divid="page_3"></div></div><scriptsrc="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:

enter image description here

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.

  1. 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.varOrderViewModel = {};
        //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 entityOrderViewModel.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.

Post a Comment for "How Can I Serialize A Form In Javascript Asp.net"