2

I have a form in my aspx markup.

I add to it some fields dynamically.

I submit them to a controller's action.

How should I read them in the server side ?

Update

  1. My form contains n textboxes.

  2. I have thought to use one model that will contain an IEnumerable<FormItem>

in the client side I'll fill it with Ajax form.

Make sense?

Elad Benda
  • 35,076
  • 87
  • 265
  • 471

3 Answers3

0

Assuming your form contains a textbox for the user to enter an e-mail address, and the markup for your form looks like this:

@using (Html.BeginForm("Index"))
{
    <!-- pretend this field was dynamically created with javascript -->
    <input id="email" type="email" name="email" />

    <button type="submit">Submit</button>
}

The value inside of the email textbox can be accessed using the Form property of the Request object:

public class HomeController : Controller
{
    [HttpPost]
    public ActionResult Index()
    {
        // Get the value of the input named `email`
        var email = Request.Form["email"];

        /* Do cool stuff because you can */
    }
}

Or, you could modify your action method to accepted a string parameter with the same name as the input:

public class HomeController : Controller
{
    [HttpPost]
    public ActionResult Index(string email)
    {
        // The default model binder will set the value of the `email` parameter to the 
        // value of the matching input from your form

        /* Do cool stuff because you can */
    }
}

There are other ways, like accepting a parameter of type FormCollection (see this example), or creating a view model class with strongly-typed

Community
  • 1
  • 1
Justin Rusbatch
  • 3,992
  • 2
  • 25
  • 43
  • Thanks. Can you elaborate on `new model class`. This is the most interesting, but its dynamic. How whould I fill List on the client side? – Elad Benda Apr 02 '12 at 19:54
0

You could use jQuery, If your fields are being dynamically created then I suppose you would pass those fields as an array. You should add a class to every new field, so you can fetch them.

<input class="dynamicInput" type="text"></input>
<input class="dynamicInput" type="text"></input>
<input class="dynamicInput" type="text"></input>
<button id="submit">submit</button>
<script type="text/javascript">
    $(function(){
        var myArray = [];
        $('#submit').on('click', function(i,val){
            //It will go through any input with a class "dynamicInput"
            $.each($('.dynamicInput'), function(){
                myArray.push($(this).val());
            });
            //We'll send our array to MyAction
            $.post('/MyController/MyAction', myArray, function(data) {
                //If your action returns a string you could handle it through "data"
                console.log(data);
            });

        });
    });
</script>

Then your action will get this array througn an http post request as a JavaScript object, you will need to deserialize it to a C# array so you can handle it in your server side:

[HttpPost]
public ActionResult MyAction(FormCollection values)
{
    var jsonArray = values["myArray"];
    var deserializer = new JavaScriptSerializer();
    var cSharpArray = deserializer.Deserialize<List<string>>(jsonArray);


    //Here you will handle your array as you wish


    //Finally you could pass a string to send a message to your form
    return Content("Message to user");
}
marcos.borunda
  • 1,486
  • 1
  • 17
  • 34
  • Wanted to do "postback" to save redudant redirect. I redirect to other page anyhow. You have an idea? – Elad Benda Apr 02 '12 at 19:51
  • You could have two actions with the same name, one for get request and the other for post request. If you use the jQuery post method, it will do a post request to your post action, the controller will do his job, and then when it finishs, you could handle it in a callback function, without redirect to other url. – marcos.borunda Apr 02 '12 at 21:13
0

I have thought to use one model that will contain an IEnumerable

Yeah, great idea. So once you have defined the FormItem class (depending on your needs) you are ready to roll:

public class FormItem
{
    public string Value { get; set; }
}

and then:

<form id="myform" action="/" method="post">
    <!-- Those inputs could be added dynamically -->
    <input type="text" name="[0].Value" />
    <input type="text" name="[1].Value" />
    <input type="text" name="[2].Value" />
    <input type="text" name="[3].Value" />

    <button type="submit">OK</button>
</form>

and finally AJAXify the form:

$(function() {
    $('#myform').submit(function() {
        var form = $(this);
        $.ajax({
            url: form.attr('action'),
            type: form.attr('method'),
            data: form.serialize(),
            success: function(result) {

            }
        });
    });
});

Make sure you checkout Phil Haack's blog post about the expected wire format for binding to lists.

Steve Sanderson's blog post post about editing a variable length list is also a must read.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928