Я пытаюсь прочитать со сканера штрих-кода для двух разных объектов. Я прочитал входные данные, используя jQuery события на keypress
, чтобы захватить ввод. На моей родительской странице у меня есть кнопка для каждого типа ввода, которая открывает модальное всплывающее окно для типа объекта, чтобы я мог различать источник. В моем модальном всплывающем окне я пытаюсь заставить AJAX вызвать действие на контроллере, чтобы прочитать ввод и заполнить объект в модели родительского представления. Я не уверен, что лучший способ go об этом.
Модель отсканированных объектов
public class KeyCardCheckOutViewModel
{
public Employee employee { get; set; }
public KeyCard keyCard { get; set; }
}
Сотрудник
public class Employee
{
public string employeeId { get; set; }//more objects to be populated by AD through controller
}
KeyCard
public class KeyCard
{
public string cardId { get; set; }
}
KeyCardCheckOut View
@model KeyCardCheckOut
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#userIdModal">
Scan ID
</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#keyCardModal">
Scan Key Card
</button>
<form method="post" asp-controller="Scanner" asp-action="Submit" id="testForm">
<label>@Model.employee.employeeId</label>
<label>@Model.keyCard.cardId</label>
<partial name="/Views/Scanner/_UserIdPartial.cshtml" for=employee />
<partial name="/Views/Scanner/_KeyCardPartial.cshtml" />
</form>
@Html.Hidden("OnScannedQRCodeUser", @Url.Action("OnScannedQRCodeUser", "Scanner"))
@Html.Hidden("OnScannedQRCodeKeyCard", @Url.Action("OnScannedQRCodeKeyCard", "Scanner"))
<script src="~/js/Scanner.js"></script>
_UserIdPartial
@model Employee
<form method="post" asp-controller="Scanner" asp-action="Submit" id="testForm">
<div class="modal" id="userIdModal" tabindex="-1" role="dialog" aria-labelledby="userIdModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="userIdModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="modalBody">
Scan the Id Card
<label>@Model.employeeId</label>
<input asp-for="employeeId" type="text" />
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" asp-controller="Scanner">Save changes</button>
</div>
</div>
</div>
</div>
</form>
Сканер. js
var _inputString = '';
(function ($) {
_timeoutHandler = 0,
_onKeypress = function (e) {
if (this._timeoutHandler) {
clearTimeout(this._timeoutHandler);
}
if (e.key != 'Enter') {
_inputString = _inputString.concat(e.key);
}
this._timeoutHandler = setTimeout($.proxy(function () {
if (_inputString.length <= 3) {
_inputString = '';
return;
}
$(e.target).trigger('altdeviceinput', _inputString);
_inputString = '';
}, this), 20);
};
$('#userIdModal').keypress(_onKeypress);
$('#keyCardModal').keypress(_onKeypress);
})($);
$('#userIdModal').on('altdeviceinput', function () {
var url = $('#OnScannedQRCodeUser').val();
scannedQRCode(url)
});
$('#keyCardModal').on('altdeviceinput', function () {
var url = $('#OnScannedQRCodeKeyCard').val();
scannedQRCode(url);
});
scannedQRCode = function (url) {
$.ajax({
type: 'POST',
url: url,
data: $('#testForm').serialize(),
//data: { encryptedJson: _inputString},
success: function (Response) {
$("#testForm").html(Response);
$("#userIdModal").modal('show');
},
error: function (Response) {
alert("Failed");
}
});
}
ScannerController
[HttpPost]
public ActionResult OnScannedQRCodeUser(Employee employee)
{
employee.employeeId = "77";
//grab employee object info
return PartialView("_UserIdPartial", employee);
}
Это позволит мне сканировать сотрудника и публиковать информацию вернуться на родительскую страницу. Затем я мог бы выбрать один из объектов, выполнить повторное сканирование, если я сканировал не тот объект, или переключаться между ними. Возможно, я ошибаюсь, но я стараюсь не использовать ViewBag
и не передавать его через URL, поскольку я остаюсь на той же странице.