I have a jQuery getJson method which correctly returns a selected CustomerID. When that happens, a button is enabled to send the CustomerID to another Controller method which would then open up a form to modify the customer.
I check the Form collection, but there is no value associated with the ID of the Collection. It simply comes out as "CustomerID" with no value.
How can I successfully pass this value to the other Controller with the Form Collection?
I know that the script section contains the var CustomerID and the BeginForm has the hiddenfield value, but obviously, there is no "linkage" between the two. I'm wondering how I can do this...
So basically, how can I get the JS variable value inside CustomerID into the Form?
@section scripts {
<script type="text/javascript">
$(function ()
{
var selID = null;
var CustomerID = null;
$("#Name").change(function ()
{
selID = $("#Name option:selected").val();
var url = '/Project/SpecificCustomer';
var param = { Id: selID };
$.getJSON(url, param, function (data)
{
var html = "<table border='1' cellpadding='3'>";
html += "<tr>";
html += "<td>" + "Customer ID: " + data.CustomerID + "</td>";
CustomerID = data.CustomerID;
html += "</tr>";
html += "<tr>";
html += "<td>" + "Email: " + data.Email + "</td>";
html += "</tr>";
html += "<tr>";
var FirstName = data.FirstName;
FirstName == null ? "" : FirstName;
var LastName = data.LastName;
LastName == null ? "" : LastName;
html += "<td>" + "Name: " + FirstName + " " + LastName + "</td>";
html += "</tr>";
html += "<tr>";
var date1 = new Date(parseInt(data.CreatedDate.substr(6)));
date1 == null ? "" : date1;
html += "<td>" + "Created: " + date1 + "</td>";
html += "</tr>";
html += "<tr>";
var date2 = new Date(parseInt(data.UpdatedDate.substr(6)));
date2 == null ? "" : date2;
html += "<td>" + "Updated: " + date2 + "</td>";
html += "</tr>";
html += "</table>";
$("#divData").html('');
$("#divData").append(html);
if (CustomerID != null)
$("#UpdateCust").prop('disabled', false);
});
});
});
</script>
}
@using (Html.BeginForm("Index", "Customer", new AjaxOptions { HttpMethod = "POST" }))
{
<fieldset>
<legend>Edit Customer</legend>
<div class="editor-field">
<input type="hidden" id="custID" name="custID" value="CustomerID" />
<input type="submit" id="UpdateCust" value='@Resources.Update' disabled="disabled" />
</div>
</fieldset>
}
public ActionResult Index(FormCollection form)
{
string custID = form["custID"];
...
It's not clear, but if the form resides on the same page as the getJSON
script, then you could change the last lines of your JavaScript to be:
if (CustomerID != null) {
$("#UpdateCust").prop('disabled', false);
$("#custID").val(data.CustomerID);
}