Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with a Large Number of Post Variables ASP.Net

Tags:

asp.net

I am running into an issue where I have multiple forms with a number of controls on them (20-40). The problem is that when I handle the postback, I need to put their values into variables and if they are not asp.net server controls (i.e select, input, etc...) I sometimes need to make sure they even exist. So, if I have a plain html checkbox, which is unchecked, it will not be posted to the server and you need to check for its existence, before being able to get its value. After that I need to pass them into a method to save to the database. The method handles all my crud and business validation. Setting this up is tedious at best and very time consuming. What are people doing to handle this? I am using ASP.Net 4.0 Web forms and VB.Net. One thought was to pass the http context into the method and let the code in the method look for the values. Still, doesn't seem that good of a solution. Any advice would really be appreciated, since I know I am not the only one who has run into this problem. Thanks in advance.

Wade

like image 522
Wade73 Avatar asked Oct 06 '22 14:10

Wade73


2 Answers

For large forms, you can:

  1. create javascript object on client, convert it to JSON string, put JSON string to ASP .NET control Hidden or invisible textarea;
  2. submit form and deserialize JSON to object on server.

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.validate.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.validation.net.webforms.min.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:HiddenField runat="server" ID="Hidden1" />
    <input type="checkbox" id="CheckBox1" checked />
    <input type="checkbox" id="CheckBox2" />
    <input type="text" id="text1" name="text1" value=""/>
    <asp:Button runat="server" Text="Button" ID="Button1" OnClientClick="createJSON()" OnClick="Button1_Click" />
    <script type="text/javascript">

        function createJSON() {
            $('#Hidden1').val(JSON.stringify({
                field1: $('#CheckBox1').is(':checked'),
                field2: $('#CheckBox2').is(':checked'),
                field3: $('#text1').val()
            }));
        }

        $(document).ready(function () {
            $("#form1").validate({
                onsubmit: false,
                rules: {
                    text1: {
                        required: true,
                        digits: true
                    }
                }
            });

            $("#Button1").click(function (evt) {
                var isValid = $("#form1").valid();
                if (!isValid) evt.preventDefault();
            });
        });
    </script>
    </form>
</body>
</html>

Default.aspx.cs

using System;
using System.Web.Script.Serialization;

public class myClass
{
    public bool field1;
    public bool field2;
    public string field3;
}

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        var result = (myClass)(new JavaScriptSerializer()).Deserialize(Hidden1.Value, typeof(myClass));
    }
}

enter image description here

enter image description here

Install validation:

PM> Install-Package JQuery.Validation

PM> Install-Package JQuery.Validation.WebForms

like image 93
Boris Gappov Avatar answered Oct 10 '22 21:10

Boris Gappov


From the moment that some controls they not post back any value, like the check box if is not checked you have two options.

  1. Know all your controls before and after the post back / or
  2. Create with javascript all the names of the controls and post them back in a hidden field.

Now, on the post back you have all the posted values on the HttpContext.Current.Request.Form where you can read them all.

On the client side you can use simple javascript or jQuery to create the list of all input controls and send them on a hidden input. Here is an example:

var inputs, index, cNames = ""; 
inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
    cNames += "&" + inputs[index].name;
}   

document.getElementById("AllControls").value = cNames;

or the same with jQuery

    var cAllNames = "";
    $('input').each(function() {
        cAllNames += "&" + $(this).attr("name");
    });
    jQuery('#AllControls').val(cAllNames);

and on your page you have a hidden control like

<input type="hidden" name="AllControls" id="AllControls" />

and on the post you have all the names of your controls in a line like:

AllControls=&__VIEWSTATE&__EVENTVALIDATION&cbBoxTest&AllControls&Button1

There you can split that string, each name is seperated with the &, and there you can see what is used, what is not. You can either pass additional informations about that controls - the same way I send the name of each.

like image 23
Aristos Avatar answered Oct 10 '22 20:10

Aristos