NIRANJAN G NIRANJAN G - 3 months ago 21
Javascript Question

How to get values of dynamically generated text box and make ajax request to controller in mvc4 and jquery?

I have one table where I am dynamically generating textbox's and binding model values to those textboxe's. Also i have one button. I want to send dynamically generated textbox values in Ajax request. My code is as below.

@foreach (var group in Model.Groups)
{
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="dataTable tableHover">
<tr>
@foreach (var item in group.Items)
{
<th>@item.Label</th>
}


</tr>
<tr>
@foreach (var item in group.Items)
{
<td><input type="text" id="Value" value="@item.Value"></td>
}

</tr>


</table>
}
@foreach (var group in Model.Groups)
{
<tr>
@{ int k = 1; }
@foreach (var item in group.Items)
{
if (k == 1)
{
<td scope="col"> <button type="button" class="btn btn-primary" id="SaveUpdate" onclick="updatemetaData('@item.upld_id,@item.Value');">Save</button></td>
k = 0;
}
}
</tr>
}


this is my jquery function to make ajax request.

function updatemetaData(docid) {
$.ajax(
{
type: "GET",
data: { upld_id: docid },
dataType: "html",
url: '/documentVerification/updatedocDetails',
headers: {
'VerificationToken': forgeryId
},
success: function (data)
{
$('#GridDetails').html("");
$('#GridDetails').html(data);
$("#dialog-formdocumentdata").dialog('open');

}
, error: function (error)
{
}
});

}

</script>


I want to send values of dynamically generated textboxes in ajax call. In the below code 2 text boxe's will generate in all cases.

@foreach (var item in group.Items)
{
<td><input type="text" id="Value" value="@item.Value"></td>
}


Is it possible in jquery to achieve this? Thank you in advance.

Answer

I can't spot a computer around. Be careful following code may contain errors.

Use nuget to import Newtonsoft Json assembly.

In the controller add:

using Newtonsoft.Json;

ViewBag.JsonData = JsonConvert.SerializeObject(yourObjectContainingRandomNumbers); 

In the view:

@Html.Hidden("inputID", Viewbag.JsonData)

Move jquery reference to the hidden field and things should work.

Comments