views:

442

answers:

4

I am developing asp.net mvc application. I have a section on the form where I add some text boxes dynamically when the user clicks a "Add New Part" button. The problem is when I submit the form I don't get the data from the fields I added dynamically. I am passing the FormCollection to my controller and stepping through the code in the debugger and those fields are not there. If I look at them in firebug I see them just fine. Any ideas?

Here is the javascript for adding the text fields to the page:

function moreFields() {
        var newFields = document.getElementById('readrootpu').cloneNode(true);
        newFields.id = '';
        newFields.style.display = 'block';
        var newField = newFields.childNodes;
        for (var i = 0; i < newField.length; i++) {
            var theName = newField[i].name
            if (theName)
                newField[i].name = theName;
        }
        var insertHere = document.getElementById('newpartusageitems');
        insertHere.parentNode.insertBefore(newFields, insertHere);
    }

Here is the html:

<div id="readrootpu" class="usedparts" style="display: none">
    <% var fieldPrefix = "PartUsage[]."; %>
    Part ID:
    <%= Html.TextBox(fieldPrefix + "ID", "")%>
    Serial Number:
    <%= Html.TextBox(fieldPrefix + "Serial", "")%>
    Quantity:
    <%= Html.TextBox(fieldPrefix + "Quantity", "") %>
    <input type="button" value="Remove" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
</div>

When I inspect the html with firebug it looks fine to me:

Part ID: <input type="text" name="PartUsage[].ID" id="PartUsage[]_ID" value="" />
Serial Number: <input type="text" name="PartUsage[].Serial" id="PartUsage[]_Serial" value="" />
Quantity: <input type="text" name="PartUsage[].Quantity" id="PartUsage[]_Quantity" value="" />

Thoughts?

A: 

You cannot just aribtrarily add text boxes client-side without having the corresponding server-side controls ready to read the data from the postback. However, you should be able to read the raw data from HttpRequest.Form.

update: oops! it's MVC. I didn't read^H^H^H^H see that. never mind.

-Oisin

x0n
I am looking at HttpRequest.Form but the fields that are added on the client side are not being sent back to the server.
Mike Roosa
@x0n: it's not asp.net webforms, it's asp.net mvc. You *can* post anything
Mauricio Scheffer
A: 

When you have multiple values on fields with same names, you should be able to see them on the server side using Request.Form.GetValues("key").

You should note that when you clone the nodes, you create copies with the same IDs, which is considered invalid.
Also, you have a for loop there, and I don't quite get what it does (reads the node's name and sets it back - what is the reason for doing that? Should that be var theName = newFields[i].name ?)

Kobi
+1  A: 

Verify with Firebug that all the post data is being sent from the page via the "Net" tab.

Also, i agree with Kobi: you need to increment the ID's on the cloned elements so they are unique.

I would suggest you look into jQuery for dynamically creating html elements. I have only just started learning jQuery and its very easy. The following code demonstrates a simple file upload form that allows the user can add more input elements dynamically. Each time the jQuery adds a new input element, i append a chr to the id attribute so they are all unique. Hopefully this helps you:

The script block for the jQuery.. notice the last part is for the ajax animation. The actual copying code is only those 4 lines from $("#moreFiles").click

    <script type="text/javascript">
        var counter = "oneFile";
        $(document).ready(function() {
            $("#moreFiles").click(function() {
                var newCounter=counter+"1";
                $("p#"+counter).after("<p id='"+newCounter+"'><input type='file' name='"+newCounter+"' id='"+newCounter+"' size='60' /></p>");
                counter=newCounter;
            });
            $("#submitUpload").click(function() {
                $("#submitUpload").val("Uploading...");
                $("img.uploadingGif").show(); 
            });
        });
    </script>

..and the aspnet markup:

    <% string postUrl = Model.PostUrl + (Model.ModelID > 0 ? "/" + Model.ModelID.ToString() : ""); %>
    <form id="uploadForm" class="uploadForm" action="<% =postUrl %>" 
        method="post" enctype="multipart/form-data">
        <label>Select file(s) for upload (size must not exceed 
            <% =Html.Encode(ServiceConstants.MAX_FILE_UPLOAD_SIZE_INBYTES) %> bytes):</label>  
        <p id="oneFile"><input type="file" name="oneFile" id="oneFile" size="60" /></p>
        <% if(Model.MultipleFiles) { %>
            <p><a id="moreFiles" href="#">add more files</a></p>
            <input id="MultipleFiles" type="hidden" name="MultipleFiles" value="true" />
        <% } %>
        <p><%--<input id="submitUpload" type="submit" value="Upload" />--%>
        <% =Html.InputSubmit("Upload","submitUpload") %>
            <% =Html.LoadingImage("uploadingGif") %>
    </form>

..this all only boils down to a few lines of html and jQuery.

cottsak
A: 

I was working with plain HTML when my form worked fine if all the fields were left blank, but it would not submit if I filled out the form. Later I realized that it was because of a text-field entry 'Email' in which I was entering an email-address containing the character '@'. When I removed the '@', the form started submitting again.

Mudit

Mudit