2017-01-29 47 views
-1

我正在学习ASP.NET MVC 5.我创建了一个视图“创建”。但我没有使用Razor来生成输入字段,我使用纯html输入。HttpPost后填充字段创建 - 对象为空使用输入

Create.cshtml

@model MyProject.Product 

<h2>Create Product</h2> 

<form method="post"> 

    Description: <br /> 
    <input type="text" name="Description" id="Description"/> <br /> 
    ValueType: <br /> 
    <input type="text" name="ValueType" id="ValueType"/> 
    <br /> 
    <input type="submit" name="btSend"/> 

</form> 

我的控制器:

public ActionResult Create() 
     {    
      return View(); 
     } 

     [HttpPost] 
     public ActionResult Create(Product product) 
     { 
      if (ModelState.IsValid) 
      {     
       db.Product.Add(product);     
       db.SaveChanges();     
       return RedirectToAction("Index"); 

      } 
      else 
      { 
       return View(product); 
      } 

    It works fine. I can create new products. 

但我需要使用一些服务器端验证与模型注解。 因此,我想发送数据,如果模型无效,请返回使用值创建。我知道如何把验证信息。所以,我试过这个:

@model MyProject.Product 

<h2>Create Product</h2> 

<form method="post"> 

    Description: <br /> 
    <input type="text" name="Description" id="Description" value="@Model.Description"/> <br /> 
    ValueType: <br /> 
    <input type="text" name="ValueType" id="ValueType" value="@Model.ValueType"/> 
    <br /> 
    <input type="submit" name="btSend"/> 

</form> 

如何将纯输入与html绑定到模型?

为什么为空值?

非常感谢。

+1

为什么在世界上你不使用剃刀?使用@ Html.LabelFor()','@ Html.TextBoxFor()'和@ Html.ValidationMessageFor()'生成你正确的控件形式,然后查看它生成的所有html,并将它与你的比较,这意味着你没有双向模型绑定,也没有验证 –

+0

因为我和前端开发人员一起工作,他们给了我创建的html。我想知道是否有办法处理输入类型。如何绑定它? – ComplexityAlg

+0

使用'HtmlHelper'方法将为您提供正确的html,这对于双向模型绑定和验证是必需的。 '@ Model.Description'是剃须刀代码,所以毫无疑问你不想使用剃须刀 –

回答

0

如果您不想使用razor based form approach,则可以使用显示验证消息和Viewbag/ViewData

[HttpPost] 
    public ActionResult Create(Product product) 
    { 
     if (!ModelState.IsValid) 
     { 
      //if you want to get validation message from ModelState itself, you can query from Modelstate : 
      string message = string.Join(" , ", ModelState.Values 
           .SelectMany(v => v.Errors) 
           .Select(e => e.ErrorMessage)); 
      ViewData["ValidationMessage"] = "Validation Message";// you can use above variable message here 
      return View(product); 
     } 
    // your other implementation 
    } 

你的观点应该是这样的:

@model MyProject.Product 

<h2>Create Product</h2> 

<form method="post"> 
    <div class="error-message">@ViewData["ValidationMessage"]</div> 
    Description: <br /> 
    <input type="text" name="Description" id="Description" value="@Model.Description"/> <br /> 
    ValueType: <br /> 
    <input type="text" name="ValueType" id="ValueType" value="@Model.ValueType"/> 
    <br /> 
    <input type="submit" name="btSend"/> 

</form> 

不过,我会建议使用razor based form approach如果你允许这样做。

+0

你的解决方案**是使用剃须刀(这就是@ViewData [“ValidationMessage”]中的@意思是 –

+0

是的,但OP已经在使用一些简单的剃须刀,比如“@Mode.Description”和“@Model.ValueType” –

+0

是的,我知道(正如我在问题的评论中指出的那样)。但是你的问题说明了如果你不喜欢不想使用剃须刀,但使用剃须刀显示解决方案: –