Bryan Bryan - 3 months ago 19
jQuery Question

Inline editing with Jquery asp.net mvc

I have the following HTML:

@using (Ajax.BeginForm("Edit", "LicenseHolder", null, new AjaxOptions()
{
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
OnSuccess = "createonsuccess"
}))
{
<table class="table table-striped editTable" style="border-top: 1px solid #000;">
<tr>
<td class="tdstyle"><span>@Model.LicenseHolder.LegalPerson.Name</span></td>
</tr>
<tr>
<td class="bigtd"></td>
</tr>
<tr>
<td class="tdstyle">
<i class="fa fa-map-marker iconPos" aria-hidden="true"></i>
<span>@Model.LicenseHolder.LegalPerson.PrimaryAddress.StreetAddress</span>
</td>
</tr>
<tr>
<td class="tdstyle"><span>@Model.LicenseHolder.LegalPerson.PrimaryAddress.ZipCode</span></td>
</tr>
<tr>
<td class="tdstyle"><span>@Model.LicenseHolder.LegalPerson.PrimaryAddress.HomeTown @Model.LicenseHolder.LegalPerson.PrimaryAddress.Country</span></td>
</tr>
</table>
}


I make the rows inline editable with this javascript code:

$('.editEnable').click(function (e) {
e.stopPropagation();
$('.editTable tr').each(function () {
var ele = $(this).find("span");
var value = ele.text();
updateVal(ele, value);
});
$('.editFields').show();
});

$('.centering').click(function (e) {
$(".thVal").replaceWith(function () {
return this.value;
});
$('.editFields').hide();
});

function updateVal(currentEle, value) {
$(currentEle).html('<input class="thVal" maxlength="4" type="text" width="2" value="' + value + '" />');
$(".thVal", currentEle).focus().keyup(function (event) {
if (event.keyCode == 13) {
$(currentEle).html($(".thVal").val().trim());
}
}).click(function (e) {
e.stopPropagation();
});
}
});


The thing I want to here Is that when I click on save, I want to make a post-call to the Edit-method:

public async Task<ActionResult> Edit(LicenseHolderDetailViewModel model)
{
return View();
}


The thing here Is that model Is null when I hit save. That because the input field Is not binded to the
LicenseHolderDetailView
. How can I accomplish this binding when I do inline editing?

Tim Tim
Answer

Span's do not post back in a form. So you cannot as currently designed.

Likely the easiest approach to solve this would be to keep hidden inputs with the span's and keep the values in sync. Make the hiddenFields have name attributes that correspond to the fields on your model.

For example

<tr>
    <td class="tdstyle">
        <span>@Model.LicenseHolder.LegalPerson.Name</span>
        @Html.HiddenFor(m => m.LicenseHolder.LegalPerson.Name)
    </td>
</tr>

Make sure to update the hidden fields or they will retain their original values.

Also note your form will need to wrap all the elements you want to submit. So now it will need to enclose your whole table to submit all of the hidden inputs.