I'm using event blur for lost focus on textbox. But I only bind data to textboxfor cannot bind data to labelfor or displayfor. How can I do ?
My java script:
$('#PGId').blur(function () {
var errormsg = "";
var id = $('#PGId').val();
$.ajax({
type: "GET",
url: '@Url.Action("GetDetailPG", "TimeSheetHeader")',
data: { pgId: id },
dataType: "json",
success: function (data) {
$("#FirstName").val(data.FisrtName)
$("#LastName").val(data.LastName)
$("#Shiff").val(data.ShiffId)
},
error: function (jqXHR, exception) {
$('#error').html("Primitive Functions not allowed.")
}
});
})
My razor view:
<div class="col-md-3 form-group">
@Html.LabelFor(model => model.PGId) <em>( * )</em>
@Html.TextBoxFor(model => model.PGId, new { @class = "form-control input-sm", @name = "normal" })
@Html.DisplayFor(model => model.FirstName) @Html.DisplayFor(model => model.LastName)
</div>
<div class="col-md-3 form-group">
@Html.LabelFor(model => model.Shiff)
<div>
<label class="radio-inline">
@Html.RadioButtonFor(model => model.Shiff, "M") Morning
</label>
<label class="radio-inline">
@Html.RadioButtonFor(model => model.Shiff, "N") Night
</label>
</div>
<span style="color:red" class="help-block">@Html.ValidationMessageFor(model => model.Shiff)</span>
</div>
@Html.DisplayFor()
does not generate an element with an id
attribute, nor a control with a value
attribute so you can't use $("#FirstName").val(data.FirstName)
. Instead create a container element with the required id
and update its contents in the ajax call (not sure what ShiffId
is - you didn't show any html for it)
@Html.TextBoxFor(m => m.PGId, new { @class = "form-control input-sm" })
<div id="firstname">@Html.DisplayFor(m => m.FirstName)</div>
<div id="lastname">@Html.DisplayFor(m => m.LastName)</div>
then in the script
success: function (data) {
$("#firstname").text(data.FirstName)
$("#lastname").text(data.LastName)
},
Note also you should be using the change
event of the textbox (not blur
) to avoid unnecessary calls to the server when the user is just tabbing through controls.
Side note: Why are you trying to override the name
attribute of the textbox for property PGId
?
Edit
Based on OP edit showing html for ShiffId
, to update the radio button, add a class name to the radio buttons (note: class
attribute added for easier selection and id
attribute added so no duplicates)
@Html.RadioButtonFor(model => model.Shiff, "M", new { id = "shiff-m", @class = "shiff" })
@Html.RadioButtonFor(model => model.Shiff, "N", new { id = "shiff-n", @class = "shiff" })
and replace $("#Shiff").val(data.ShiffId)
with (assumes data.Shiff
will be either "M" or "N")
$('.shiff[value="' + data.Shiff + '"]').prop('checked', true);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.