我正在使用Razor Pages开发ASP.NET Core网页。在一页上,添加或选择了一个客户,并且在OnGet函数中正确传递了customer_id(通过调试看到)。然后,当我让用户填写表单时,我尝试使用Entity Framework调用SQL Server数据库。一切都应该正常工作,但是,在OnPostAsync()中,当我尝试导入在OnGet()中设置的customer_id值时,出现错误,因为该值以某种方式被设置为0,而不是先前设置为的值。 。我不知道为什么会这样,因为我通常是Razor Pages和Entity Framework的新手,但是我在下面发布了代码。任何建议都很棒!
AddAssessment.cshtml.cs:
namespace CustomerPageTest.Pages.Assessment
{
public class AddAssessmentModel : PageModel
{
private readonly CustomerPageTest.Data.CustomerPageTestContext _context;
public AddAssessmentModel(CustomerPageTest.Data.CustomerPageTestContext context)
{
_context = context;
}
public static List<SelectListItem> InDatabaseUserData()
{
List<SelectListItem> Users = new List<SelectListItem>();
string connString = "Data Source = DESKTOP-5A23I9M; Initial Catalog = DataWarehouse; User ID = sa; pwd = 2128Swan";
string commandString = "SELECT user_id, name FROM KelderUser";
SqlConnection conn = new SqlConnection(connString);
SqlDataAdapter adapter = new SqlDataAdapter(commandString, conn);
DataTable dtCustomers = new DataTable();
adapter.Fill(dtCustomers);
foreach (DataRow dataRow in dtCustomers.Rows)
{
SelectListItem temp = new SelectListItem()
{
Value = dataRow[0].ToString(),
Text = dataRow[1].ToString()
};
Users.Add(temp);
}
return Users;
}
[BindProperty]
public CustomerPageTest.Assessment Assessment { get; set; } = new CustomerPageTest.Assessment();
public List<SelectListItem> SelectUser { get; set; } = new List<SelectListItem>();
public void OnGet(int customerId)
{
SelectUser = InDatabaseUserData();
Assessment.customer_id = customerId;
if(Assessment == null)
{
return RedirectToPage("/Customer/List");
}
return Page();
}
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details, see https://aka.ms/RazorPagesCRUD.
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
foreach(var item in SelectUser)
{
if (item.Selected)
{
try { Assessment.user_id = Convert.ToInt32(item.Value); } catch (Exception) { }
}
}
try { Assessment.imported_data_datetime = Convert.ToDateTime(Assessment.imported_data_datetime); } catch(Exception) { }
_context.Assessment.Add(Assessment);
await _context.SaveChangesAsync();
return RedirectToPage("/Customer/List");
}
}
}
然后添加AddCustomer.cshtml:
@page
@model CustomerPageTest.Pages.Assessment.AddAssessmentModel
@{
ViewData["Title"] = "AddAssessment";
}
<h1>AddAssessment</h1>
<h4>Assessment</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Assessment.vcenter" class="control-label"></label>
<input asp-for="Assessment.vcenter" class="form-control" />
<span asp-validation-for="Assessment.vcenter" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Assessment.imported_data_datetime" class="control-label"></label>
<input asp-for="Assessment.imported_data_datetime" class="form-control" />
<span asp-validation-for="Assessment.imported_data_datetime" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Assessment.notes" class="control-label"></label>
<input asp-for="Assessment.notes" class="form-control" />
<span asp-validation-for="Assessment.notes" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Assessment.user_id"></label>
<select class="form-control" asp-for="Assessment.user_id" asp-items="Model.SelectUser">
<option value="">Select a User</option>
</select>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-page="/Customer/List">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
此外,如果您对我的代码中发生的事情有任何疑问,请告诉我,因为在此之前还有其他类和页面。主要思想是我有一个带有整数的评估类:customer_id,需要设置它并且没有设置它。
答案 0 :(得分:0)
发生这种情况的原因是因为HTTP是无状态的。处理完一个请求后,您在一个请求中创建的任何状态(数据)都会被销毁,除非您采取措施将其保留。
有多种方法可以管理Razor页面(https://www.learnrazorpages.com/razor-pages/state-management)中的状态,但在这种情况下,您应该使用隐藏的表单字段,将选定的客户ID发布到OnPost处理程序中
答案 1 :(得分:0)
我编写了一个演示,发现您没有在cshtml中绑定customer_id,因此当您将日期发布到cshtml.cs时,您没有发布customer_id。您可以在其中添加<input hidden asp-for="Assessment.customer_id" class="form-control" />
cshtml来绑定customer_id。
这是一个演示作品:
cshtml:
<div class="row">
<div class="col-md-4">
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Assessment.vcenter" class="control-label"></label>
<input asp-for="Assessment.vcenter" class="form-control" />
<span asp-validation-for="Assessment.vcenter" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Assessment.imported_data_datetime" class="control-label"></label>
<input asp-for="Assessment.imported_data_datetime" class="form-control" />
<span asp-validation-for="Assessment.imported_data_datetime" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Assessment.notes" class="control-label"></label>
<input asp-for="Assessment.notes" class="form-control" />
<span asp-validation-for="Assessment.notes" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Assessment.user_id"></label>
<select class="form-control" asp-for="Assessment.user_id" asp-items="Model.SelectUser">
<option value="">Select a User</option>
</select>
</div>
<input hidden asp-for="Assessment.customer_id" class="form-control" />
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
cshtml.cs:
public class AddCustomerModel : PageModel
{
[BindProperty]
public Assessment Assessment { get; set; } = new Assessment();
public List<SelectListItem> SelectUser { get; set; } = new List<SelectListItem>();
public IActionResult OnGet()
{
for (int i = 1; i < 6; i++) {
SelectListItem temp = new SelectListItem()
{
Value = i+"",
Text = "user"+i
};
SelectUser.Add(temp);
}
Assessment.customer_id = 2;
Assessment.vcenter = "vcenter";
return Page();
}
public IActionResult OnPost() {
if (!ModelState.IsValid)
{
return Page();
}
return Page();
}
}