C# 在blazor项目中使用api时网格中的特定行出现问题
我在DevExpress网格中的特定行正确连接到API时遇到问题 我相信问题出在API上,因为我可以通过删除或编辑网格中的某些行来进行操作。但是上面提到的其他行无法编辑或删除,但创建的所有新数据也可以进行操作。希望有人有这个问题是为了,我提供了一些代码和错误消息给你们看 网格的代码C# 在blazor项目中使用api时网格中的特定行出现问题,c#,api,blazor,dx-data-grid,C#,Api,Blazor,Dx Data Grid,我在DevExpress网格中的特定行正确连接到API时遇到问题 我相信问题出在API上,因为我可以通过删除或编辑网格中的某些行来进行操作。但是上面提到的其他行无法编辑或删除,但创建的所有新数据也可以进行操作。希望有人有这个问题是为了,我提供了一些代码和错误消息给你们看 网格的代码 @page "/FetchData" @inject HttpClient Http <h2>DevExpress Data Grid:</h2> @if (customer == null
@page "/FetchData"
@inject HttpClient Http
<h2>DevExpress Data Grid:</h2>
@if (customer == null)
{
<h1>thinking!?!?!?</h1>
}
else
{
<DxDataGrid Data=@customer
DataNavigationMode="@DataGridNavigationMode.VirtualScrolling"
RowRemoving=@((dataItem) => OnRowRemoving(dataItem))
RowUpdating=@((updatingDataItem, newValues) => OnRowUpdating(updatingDataItem, newValues))
RowInserting=@((newValues) => OnRowInserting(newValues))>
<DxDataGridCommandColumn Width="150px"></DxDataGridCommandColumn>
<DxDataGridColumn Field=@nameof(Customer.CustomerId) Caption="ID"></DxDataGridColumn>
<DxDataGridColumn field=@nameof(Customer.FirstName) Caption="FirstName"></DxDataGridColumn>
<DxDataGridColumn Field=@nameof(Customer.LastName) Caption="LastName"></DxDataGridColumn>
</DxDataGrid>
<br />
<br />
<DxDataGrid Data=@customer
PageSize=15
RowRemoving=@((dataItem) => OnRowRemoving(dataItem))
RowUpdating=@((updatingDataItem, newValues) => OnRowUpdating(updatingDataItem, newValues))
RowInserting=@((newValues) => OnRowInserting(newValues))>
<DxDataGridCommandColumn Width="150px"></DxDataGridCommandColumn>
<DxDataGridColumn Field=@nameof(Customer.CustomerId) Caption="ID"></DxDataGridColumn>
<DxDataGridColumn field=@nameof(Customer.FirstName) Caption="FirstName"></DxDataGridColumn>
<DxDataGridColumn Field=@nameof(Customer.LastName) Caption="LastName"></DxDataGridColumn>
</DxDataGrid>
}
@functions {
Customer[] customer;
Customer cust = new Customer();
private const string APIServer = "http://Notrealapi.com/api/customers/";
protected override async Task OnInitAsync()
{
customer = await Http.GetJsonAsync<Customer[]>("http://Notrealapi.com/api/customers/");
}
async void OnRowRemoving(Customer dataItem)
{
await Http.DeleteAsync("http://Notrealapi.com/api/customers/" + dataItem.CustomerId);
customer = await Http.GetJsonAsync<Customer[]>("http://Notrealapi.com/api/customers/");
StateHasChanged();
}
async void OnRowUpdating(Customer dataItem, Dictionary<string, object> newValue)
{
Dictionary<string, object> tempNewValues = new Dictionary<string, object>(newValue);
cust = await Http.GetJsonAsync<Customer>("http://Notrealapi.com/api/customers/" + dataItem.CustomerId);
foreach (var field in tempNewValues.Keys)
{
switch (field)
{
case "ID":
dataItem.CustomerId = (int)tempNewValues[field];
break;
case "FirstName":
dataItem.FirstName = (string)tempNewValues[field];
break;
case "LastName":
dataItem.LastName = (string)tempNewValues[field];
break;
}
}
//dataItem.FirstName = cust.FirstName;
//dataItem.LastName = cust.LastName;
await Http.SendJsonAsync(HttpMethod.Put, "http://Notrealapi.com/api/customers/" + dataItem.CustomerId, dataItem);
cust = new Customer();
customer = await Http.GetJsonAsync<Customer[]>("http://Notrealapi.com/api/customers/");
StateHasChanged();
}
async void OnRowInserting(Dictionary<string, object> newValue)
{
Dictionary<string, object> tempNewValues = new Dictionary<string, object>(newValue);
cust = new Customer();
await Http.SendJsonAsync(HttpMethod.Post, "http://Notrealapi.com/api/customers/", tempNewValues);
cust = new Customer();
customer = await Http.GetJsonAsync<Customer[]>("http://Notrealapi.com/api/customers/");
StateHasChanged();
}
public class Customer
{
public int CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zipcode { get; set; }
}
}
@page”/FetchData
@注入HttpClient Http
DevExpress数据网格:
@如果(客户==null)
{
思考
}
其他的
{
OnRowRemoving(数据项))
RowUpdate=@((UpdateDataItem,newValues)=>OnRowUpdate(UpdateDataItem,newValues))
行插入=@((新值)=>OnRowInserting(新值))>
OnRowRemoving(数据项))
RowUpdate=@((UpdateDataItem,newValues)=>OnRowUpdate(UpdateDataItem,newValues))
行插入=@((新值)=>OnRowInserting(新值))>
}
@功能{
客户[]客户;
客户客户=新客户();
私有常量字符串APIServer=”http://Notrealapi.com/api/customers/";
受保护的重写异步任务OnInitAsync()
{
customer=wait Http.GetJsonAsync(“http://Notrealapi.com/api/customers/");
}
异步void OnRowRemoving(客户数据项)
{
等待Http.DeleteAsync(“http://Notrealapi.com/api/customers/“+dataItem.CustomerId);
customer=wait Http.GetJsonAsync(“http://Notrealapi.com/api/customers/");
StateHasChanged();
}
异步void onrowUpdate(客户数据项、字典newValue)
{
Dictionary tempNewValues=新字典(newValue);
cust=wait Http.GetJsonAsync(“http://Notrealapi.com/api/customers/“+dataItem.CustomerId);
foreach(tempNewValues.Keys中的var字段)
{
开关(现场)
{
案例“ID”:
dataItem.CustomerId=(int)tempNewValues[field];
打破
案例“名字”:
dataItem.FirstName=(字符串)tempNewValues[字段];
打破
案例“LastName”:
dataItem.LastName=(字符串)tempNewValues[字段];
打破
}
}
//dataItem.FirstName=cust.FirstName;
//dataItem.LastName=cust.LastName;
等待Http.SendJsonAsync(HttpMethod.Put,“http://Notrealapi.com/api/customers/“+dataItem.CustomerId,dataItem);
cust=新客户();
customer=wait Http.GetJsonAsync(“http://Notrealapi.com/api/customers/");
StateHasChanged();
}
异步void OnRowInserting(字典newValue)
{
Dictionary tempNewValues=新字典(newValue);
cust=新客户();
等待Http.SendJsonAsync(HttpMethod.Post)http://Notrealapi.com/api/customers/“,tempNewValues);
cust=新客户();
customer=wait Http.GetJsonAsync(“http://Notrealapi.com/api/customers/");
StateHasChanged();
}
公共类客户
{
public int CustomerId{get;set;}
公共字符串名{get;set;}
公共字符串LastName{get;set;}
公共字符串电子邮件{get;set;}
公用字符串电话{get;set;}
公共字符串地址{get;set;}
公共字符串City{get;set;}
公共字符串状态{get;set;}
公共字符串Zipcode{get;set;}
}
}
API中的一些代码
Customer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace testsitegp.Models
{
public partial class Customer
{
public Customer()
{
Order = new HashSet<Order>();
}
public int CustomerId { get; set; }
[StringLength(50)]
public string FirstName { get; set; }
[StringLength(50)]
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zipcode { get; set; }
public ICollection<Order> Order { get; set; }
}
}
使用系统;
使用System.Collections.Generic;
使用System.ComponentModel.DataAnnotations;
命名空间testsitegp.Models
{
公共部分类客户
{
公众客户()
{
顺序=新的HashSet();
}
public int CustomerId{get;set;}
[长度(50)]
公共字符串名{get;set;}
[长度(50)]
公共字符串LastName{get;set;}
公共字符串电子邮件{get;set;}
公用字符串电话{get;set;}
公共字符串地址{get;set;}
公共字符串City{get;set;}
公共字符串状态{get;set;}
公共字符串Zipcode{get;set;}
公共ICollection顺序{get;set;}
}
}
CustomerController.cs
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Net;
using testsitegp.Models;
using testsitegp.contracts;
using Microsoft.AspNetCore.Cors;
namespace HPlusSportsAPI.Controllers
{
[Produces("application/json")]
[Route("api/Customers")]
public class CustomersController : Controller
{
private readonly ICostomerRepository _customerRepository;
public CustomersController(ICostomerRepository costomerRepository)
{
_customerRepository = costomerRepository;
}
private async Task<bool> CustomerExists(int id)
{
return await _customerRepository.Exists(id);
}
//[EnableCors("AnotherPolicy")]
[HttpGet]
[Produces(typeof(DbSet<Customer>))]
public IActionResult GetCustomer()
{
var results = new ObjectResult(_customerRepository.GetAll())
{
StatusCode = (int)HttpStatusCode.OK
};
Request.HttpContext.Response.Headers.Add("X-Total-Count", _customerRepository.GetAll().Count().ToString());
return results;
}
//[EnableCors("AnotherPolicy")]
[HttpGet("{id}")]
[Produces(typeof(Customer))]
public async Task<IActionResult> GetCustomer([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var customer = await _customerRepository.Find(id);
if (customer == null)
{
return NotFound();
}
return Ok(customer);
}
//[EnableCors("AnotherPolicy")]
[HttpPut("{id}")]
[Produces(typeof(Customer))]
public async Task<IActionResult> PutCustomer([FromRoute] int id, [FromBody] Customer customer)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != customer.CustomerId)
{
return BadRequest();
}
try
{
await _customerRepository.Update(customer);
return Ok(customer);
}
catch (DbUpdateConcurrencyException)
{
if(!await CustomerExists(id))
{
return NotFound();
}
else
{
throw;
}
}
}
//[EnableCors("AnotherPolicy")]
[HttpPost]
[Produces(typeof(Customer))]
public async Task<IActionResult> PostCustomer([FromBody] Customer customer)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
await _customerRepository.Add(customer);
return CreatedAtAction("GetCustomer", new { id = customer.CustomerId }, customer);
}
//[EnableCors("AnotherPolicy")]
[HttpDelete("{id}")]
[Produces(typeof(Customer))]
public async Task<IActionResult> DeleteCustomer([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (! await CustomerExists(id))
{
return NotFound();
}
await _customerRepository.Remove(id);
return Ok();
}
}
}
使用System.Linq;
使用System.Threading.Tasks;
使用Microsoft.AspNetCore.Mvc;
使用Microsoft.EntityFrameworkCore;
Net系统;
使用testsitegp.Models;
使用testsitegp.contracts;
使用Microsoft.AspNetCore.Cors;
命名空间hplusportsapi.Controllers
{
[产生(“应用程序/json”)]
[路线(“api/客户”)]
公共类CustomerController:控制器
{
私有只读ICostomerRepository\u customerRepository;
公共CustomerController(ICostomerRepository costomerRepository)
{
_customerRepository=客户存储库;
}
专用异步任务CustomerExists(int id)
{
return wait_customerRepository.Exists(id);
}
//[使能公司(“其他政策”)]
[HttpGet]
[产生(类型(DbSet))]
public IActionResult GetCustomer()
{
var results=newObjectResult(_customerRepository.GetAll())
{
StatusCode=(int)HttpStatusCode.OK
};
Request.HttpContext.Response.Headers.Add(“X-Total-Count”,_customerRepository.GetAll().Count().ToString());
返回结果;
}
//[使能公司(“其他政策”)]
[HttpGet(“{id}”)]
[产品(类型(客户))]
公共异步任务GetCustomer([FromRoute]int id)
{
如果(!ModelState.IsValid)
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using testsitegp.contracts;
using testsitegp.Models;
namespace testsitegp.repository
{
public class CustomerRepository : ICostomerRepository
{
private H_Plus_SportsContext _context;
public CustomerRepository(H_Plus_SportsContext context)
{
_context = context;
}
public async Task<Customer> Add(Customer customer)
{
await _context.Customer.AddAsync(customer);
await _context.SaveChangesAsync();
return customer;
}
public async Task<bool> Exists(int id)
{
return await _context.Customer.AnyAsync(c => c.CustomerId == id);
}
public async Task<Customer> Find(int id)
{
return await _context.Customer.Include(customer => customer.Order).SingleOrDefaultAsync(a => a.CustomerId == id);
}
public IEnumerable<Customer> GetAll()
{
return _context.Customer;
}
public async Task<Customer> Remove(int id)
{
var customer = await _context.Customer.SingleAsync(a => a.CustomerId == id);
_context.Customer.Remove(customer);
await _context.SaveChangesAsync();
return customer;
}
public async Task<Customer> Update(Customer customer)
{
_context.Customer.Update(customer);
await _context.SaveChangesAsync();
return customer;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using testsitegp.Models;
using testsitegp.contracts;
using testsitegp.repository;
using H_Plus_Sports.Contracts;
using H_Plus_Sports.Repositories;
namespace testsitegp
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ICostomerRepository, CustomerRepository>();
services.AddScoped<IOrderItemRepository, OrderItemRepository>();
services.AddScoped<IOrderRepository, OrderRepository>();
services.AddScoped<IProductRepository, ProductRepository>();
services.AddScoped<ISalespersonRepository, SalespersonRepository>();
// services.AddCors(options =>
//{
//options.AddPolicy(MyAllowSpecificOrigins,
// builder =>
//{
//builder.WithOrigins("https://websitetestgp.azurewebsites.net",
//"https://websitetest22.azurewebsites.net",
//"https://websitetest23.azurewebsites.net",
//"http://goodtest.com",
// "http://localhost:57870")
//.AllowAnyHeader()
//.AllowAnyMethod();
//});
// options.AddPolicy("AnotherPolicy",
// builder =>
//{
//builder.WithOrigins("https://websitetestgp.azurewebsites.net",
//"https://websitetest22.azurewebsites.net",
//"https://websitetest23.azurewebsites.net",
//"http://goodtest.com",
//"http://localhost:57870")
//.AllowAnyHeader()
//.AllowAnyMethod();
// });
// });
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
var connection = "Server=tcp:testsitegp.database.windows.net,1433;Initial Catalog=H_Plus_Sports;Persist Security Info=False;" +
"User ID=_____;Password=______;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
services.AddDbContext<H_Plus_SportsContext>(options => options.UseSqlServer(connection));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
//app.UseCors(MyAllowSpecificOrigins);
app.UseHttpsRedirection();
app.UseMvc();
}
}
}