Skip to main content
 首页 » 编程设计

c#之我无法从 Controller 中的表单接收发布数据

2024年02月13日14wuhuacong

当发布 html 表单时,我可以在 Controller 中看到 null,因此我无法将产品添加到数据库中。这里有什么问题?

public partial class Product 
{ 
    public int ProductId { get; set; } 
    public string Name { get; set; } 
} 
 
 
 
 
 
    public ActionResult CreateProduct() 
    { 
        return View(); 
    } 
 
    [HttpPost] 
    public ActionResult CreateProduct(Product product) // this is always null 
    { 
        service.CreateProduct(product); 
        return RedirectToAction("Index"); 
    } 
 
 
 
@model WebApplication1.Models.Product 
 
@{ 
    ViewBag.Title = "CreateProduct"; 
} 
 
<h2>CreateProduct</h2> 
@using (Html.BeginForm()) 
{ 
    @Html.ValidationSummary(true) 
    <fieldset> 
        @Html.LabelFor(model => model.Name) 
 
        @Html.EditorFor(model => model.Name) 
        @Html.ValidationMessageFor(model => model.Name) 
 
        <input type="submit" value="Create" /> 
 
    </fieldset> 
} 

请您参考如下方法:

在您的 get 中传递带有空值的模型

public ActionResult CreateProduct() 
{ 
    Product prd= new Product(); 
    return View(prd); 
} 

并检查这是否解决了您的问题