I am trying to enable an edit button to use Javascript, to post a json query to my MVC controller to get data, and then populate a form, client side, with data returned from the json query. And I am failing. And I am not sure I am doing the right way.
I am showing a list of 'Sub Categories' on my view.
@foreach (var sub in Model.SubCategories)
{
<div class="row">
<div class="col-sm-3">
@Html.ActionLink(" ", "DeleteSubCategory", "Category", new { subCategoryId = sub.Id }, new {@class="glyphicon glyphicon-remove", @title="Delete"})
<a href="#" class="glyphicon glyphicon-edit btnEditSubCategory" onclick="populateSubCategory(@sub.Id);"></a>
@sub.Description
</div>
</div>
}
The <a href is where I am going very wrong. I want that to call my javascript, which is where I am probably going even MORE wrong, which si supposed to take the id from the link above, go to the controller, grab the data I need based on the id, and then populate an editbox.
<script type="text/javascript">
function populateSubCategory(id) {
alert(id);
$.ajax({
url: '@Url.Action("EditSubCategory", "Category")',
type: "POST",
contentType: "application/json",
data: JSON.stringify(id),
cache: false,
async: false,
success: function (result) {
if (result.Success == 'true') {
document.getElementById("txtSubCategoryName").value = result.Description;
window.location = '@Url.Action("EditCategory", "Category", new { categoryId = Model.Id })';
} else {
alert(result.Message);
}
},
error: function () {
alert("Oh no...");
}
});
return (false);
}
I believe my javascript is probably wrong as well.
Can someone assist me with fixing this?
What happens at the moment, is that my value in my controller is null:
public JsonResult EditSubCategory(string subCategoryId)
{
var result = new { Success = "true", Description = "Test Description" };
var r = new JsonResult
{
Data = result
};
return r;
}
Note, my controller does nothing right now. I am just trying to populate the text box. But subCategoryId is always null.
Additionally, when I try assign the value, I get:
JavaScript runtime error: Unable to set property 'value' of undefined or null reference
The form that has the edit boxes I want to populate is this:
<form class="form-horizontal well">
<div class="form-group">
<label for="txtSubCategoryName" class="col-lg-4 control-label">Sub Category Name:</label>
<div class="col-lg-8">
<input type="text" class="txtSubCategoryName form-control" placeholder="The description of the Sub Category" />
</div>
</div>
<div class="form-group">
<label for="cmbCostCentre" class="col-lg-4 control-label">Default Cost Centre:</label>
<div class="col-lg-8">
<select class="form-control cmbCostCentre">
<option value="0">None</option>
@foreach (var cc in Model.AvailableCostCentres)
{
<option value="@cc.Value">@cc.Text</option>
}
</select>
</div>
</div>
</form>