Привет, поэтому я пытаюсь предварительно заполнить строку данными из моей модели. Следуя некоторым руководствам, я добился определенного прогресса, но в настоящее время получаю сообщение об ошибке «uncaught referenceerror: модель не определена». Я видел подобные вопросы, опубликованные, но до сих пор, кажется, не понимаю, как исправить мою ошибку. Мой код выглядит следующим образом:
<tbody>
<tr>
<td>
<select class = "btn btn-success " id = "productOptions" onchange = "changeDropDownValue(this)">
@* <option value = "">Product</option>*@
@foreach (var product in Model.Product)
{
<option value = "@product.ID">@product.Name</option>
}
</select>
</td>
<td>
<input asp-for = "Product[0].Description" id = "test" disabled />
<span asp-validation-for = "Product[0].Description" class = "text-danger"></span>
</td>
<td>
<input asp-for = "Product[0].Quantity" />
<span asp-validation-for = "Product[0].Quantity" class = "text-danger"></span>
</td>
<td>
<input asp-for = "Product[0].UnitPrice" disabled />
<span asp-validation-for = "Product[0].UnitPrice" class = "text-danger"></span>
</td>
<td>
<input asp-for = "Product[0].Discount" />
<span asp-validation-for = "Product[0].Discount" class = "text-danger"></span>
</td>
<td>
<input asp-for = "Product[0].Vat" disabled />
<span asp-validation-for = "Product[0].Vat" class = "text-danger"></span>
</td>
<td>
<input asp-for = "Product[0].NetTotal" disabled />
<span asp-validation-for = "Product[0].NetTotal" class = "text-danger"></span>
</td>
<ttd>
</ttd>
</tr>
</tbody>
<script>
function changeDropDownValue(test) {
var selectedProductId = document.getElementById("productOptions").value;
// Find the product with the matching ID in the Model.Product array
var selectedProduct = Model.Product.find(product => product.ID == selectedProductId);
// Update the input fields with the values of the selected product
document.getElementById("test").value = selectedProduct.Description;
document.getElementById("Product[0].Quantity").value = selectedProductId.Quantity;
document.getElementById("Product[0].UnitPrice").value = selectedProductId.UnitPrice;
document.getElementById("Product[0].Discount").value = selectedProductId.Discount;
document.getElementById("Product[0].Vat").value = selectedProductId.Vat;
document.getElementById("Product[0].NetTotal").value = selectedProductId.NetTotal;
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using DotComFinal.Data;
using DotComFinal.Models;
namespace DotComFinal.Pages.Quotations
{
public class CreateModel : SelectListPageModel
{
private readonly DotComFinal.Data.ApplicationDbContext _context;
public CreateModel(DotComFinal.Data.ApplicationDbContext context)
{
_context = context;
}
[BindProperty]
public Quotation Quotation { get; set; }
[BindProperty]
public List<Product> Product { get; set; }
public IActionResult OnGet()
{
Product = _context.Products.ToList();
Product.Insert(0, new Product { ID = 0, Name = "Select New Product" });
PopulateDropDownList(_context);
return Page();
}
// To protect from overposting attacks, see https://aka.ms/RazorPagesCRUD
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
_context.Quotations.Add(Quotation);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
}
}
I know my error is in the script but cant source a solution. THanks in advance for the assistance
Ошибка возникает, когда я пытаюсь изменить параметр «выбрать» и его функцию «changeDropDownValue (это)»
uncaught referenceerror: модель не определена
Ошибка вызвана тем, что вы используете код С# (Model.Product.find) с переменной js (selectedProductId).
Вы можете попробовать установить переменную js с переменной c#, а поскольку var selectedProduct = Model.Product.find(product => product.ID == selectedProductId);
сгенерирует атрибут имени с asp-for = "Product[0].Quantity"
, вам нужно использовать Product[0].Quantity"
:
@using Newtonsoft.Json;
@section Scripts{
<script>
function changeDropDownValue(test) {
var selectedProductId = document.getElementById("productOptions").value;
var Products = @Html.Raw(JsonConvert.DeserializeObject(JsonConvert.SerializeObject(@Model.Product)));
// Find the product with the matching ID in the Model.Product array
var selectedProduct = Products.find(product => product.ID == selectedProductId);
// Update the input fields with the values of the selected product
document.getElementById("test").value = selectedProduct.Description;
document.getElementsByName("Product[0].Quantity")[0].value = selectedProduct.Quantity;
document.getElementsByName("Product[0].UnitPrice")[0].value = selectedProduct.UnitPrice;
document.getElementsByName("Product[0].Discount")[0].value = selectedProduct.Discount;
document.getElementsByName("Product[0].Vat")[0].value = selectedProduct.Vat;
document.getElementsByName("Product[0].NetTotal")[0].value = selectedProduct.NetTotal;
}
</script>
}
Единственная проблема .... она меняет только первую строку. Открою новый вопрос, если я не могу понять это самостоятельно. Собираюсь сначала попробовать. Но он делает то, что я хочу, иначе
"uncaught referenceerror: Model is not defined "
Что касается ошибки, можете ли вы подробнее рассказать, когда и в какой строке вы получите ошибку?