저는 MVC를 처음 접했고 JQuery를 처음 사용했습니다. 드롭 다운 목록 선택에 따라 텍스트 상자를 채우려 고합니다. 내 제품 모델에는 ProductId, Name 및 Price 필드가 있습니다. 선택한 제품 이름에 따라 QuoteDetails의 ProductId 및 Price 필드를 채우고 싶습니다. 내 컨트롤러 작업은 다음과 같습니다.
public ActionResult AddProduct(int quoteId, int quoteDetailId)
{
var items = db.Products.ToList();
ViewBag.ProductData = items;
ViewData["QuoteId"] = quoteId;
ViewData["QuoteDetailId"] = quoteDetailId;
return PartialView("EditQuoteDetail", new QuoteDetail { QuoteId = quoteId, QuoteDetailId = quoteDetailId, ProductId = 1, ProductName = " ", Amount = 1, ListPrice = 0, Discount = 0, Price = 0 });
}
부분보기 EditQuoteDetail의 관련 부분은 다음과 같습니다.
@Html.HiddenFor(model => model.QuoteId, new { htmlAttributes = new { @class = "form-control" } })
@Html.HiddenFor(model => model.QuoteDetailId, new { htmlAttributes = new { @class = "form-control" } })
@Html.EditorFor(model => model.ProductId, new { htmlAttributes = new { @id="ProductId", @class = "form-control" } })
@Html.DropDownList("ProductName", new SelectList(ViewBag.ProductData, "Name", "Name"), new { @id = "ProductName" })
@Html.EditorFor(model => model.Amount, new { htmlAttributes = new { @class = "form-control" } })
@Html.EditorFor(model => model.ListPrice, new { htmlAttributes = new { @id="Price", @class = "form-control" } })
@Html.EditorFor(model => model.Discount, new { htmlAttributes = new { @class = "form-control" } })
@Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control" } })
ProductId 및 Price 필드를 채우는 데 사용하는 스크립트는 다음과 같습니다.
<script type="text/javascript">
$(document).ready(function () {
$('#ProductName').change(function () {
$('#ProductId').val($(this).val());
$('#Price').val($(this).val());
});
});
</script>
하지만 드롭 다운 목록을 선택해도 아무 일도 일어나지 않습니다. 내가 도대체 뭘 잘못하고있는 겁니까? 어떤 도움이라도 대단히 감사하겠습니다.
드디어 답을 찾았습니다. travis.js는 BeginCollectionItem 도우미가 내 HTML을 추월하고 있다고 말했을 때 올바른 경로로 나를 시작했기 때문에 ID 포함 구문을 사용하여 작동해야했습니다. 작동하는 jQuery (부모보기에서)는 다음과 같습니다.
<script type="text/javascript">
$(document).ready(function () {
$(document).on("change", '[id*="ProductList"]', function () {
$.post("/QuoteViewModel/GetProduct", { pId: $(this).val() }, function (data) {
$("[id*='ProductId']").val(data.ProductId);
$("[id*='Price']").val(data.Price);
});
});
});
</script>
컨트롤러 작업 (Usman에게 감사)은 다음과 같습니다.
[HttpPost]
public ActionResult GetProduct(int pId)
{
var data = db.Products.Find(pId);
return Json(data);
}
아휴!
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다