无法将数据从视图发送到控制器 Action .NET MVC

Posted

技术标签:

【中文标题】无法将数据从视图发送到控制器 Action .NET MVC【英文标题】:Unable to Send Data From View To controller Action .NET MVC 【发布时间】:2017-10-23 09:49:23 【问题描述】:

只是将一个 int 数据从 View 发送到 Controller Action。但控制器操作未接收到该 int 数据/无法映射该 int 数据。

我的控制器 =>

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult ConfirmNewBatchRequest(int? id)
    
        if ((id?? 0) == 0)
        
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        

        Studentassignbatche ConfirmStudentassignbatche = db.Studentassignbatches.Find(id);
        Batche FindBatche = db.Batches.Find(ConfirmStudentassignbatche.batch_code);

        if (ConfirmStudentassignbatche == null)
        
            return HttpNotFound();
        

        ConfirmStudentassignbatche.StatusCode = 1;
        db.Financeofstudents.Add(new Financeofstudent()
        
            UserId = ConfirmStudentassignbatche.UserId,
            batch_code = ConfirmStudentassignbatche.batch_code,
            debit = FindBatche.amount,
            credit = 0,
            balance = FindBatche.amount,
            lastTrunsaction = DateTime.Now,
            entry_date = DateTime.Now
        );
        TryUpdateModel(ConfirmStudentassignbatche, new string[]  "StatusCode" );
        db.SaveChanges();

        TempData["BatchConfirmSuccess"] = "Success";
        return RedirectToAction("Index");
    

我的看法 =>

    @using Something
    @model IEnumerable<Studentassignbatche>

    @
        ViewBag.Title = "Confirm New Batch Request From Student";
        IEnumerable<Course> CoursesTable = TempData["Courses"] as IEnumerable<Course>;
        IEnumerable<UserDetail> UserDetailTable = TempData["UserDetails"] as IEnumerable<UserDetail>;
    

    @section PageDescription
        <section class="content-header">
            <h1>
                @ViewBag.Title
                <small>Tsms-admin</small>
            </h1>
        </section>
    

    &nbsp;

    <div class="table-responsive">
        <table class="table table-striped table-inverse table-bordered">
            <tr>
                <th>#</th>
                <th>
                    @html.DisplayNameFor(model => model.UserId)
                </th>
                <th>
                    @Html.Label("Student Name")
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.batch_code)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.name)
                </th>
                <th>
                    @Html.Label("Vendor Name")
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.adding_date)
                </th>
                <th></th>
            </tr>
            @
                int counter = 1;
            
            @foreach (var item in Model)
            
                <tr>
                    <td>
                        @counter
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.UserId)
                    </td>
                    <td>
                        @
                            var UserDetailsId = UserDetailTable.Where(x => x.UserId == item.UserId).Select(x => x.id).FirstOrDefault();
                            var name = UserDetailTable.Where(x => x.UserId == item.UserId).Select(x => x.fullname).FirstOrDefault();
                        
                        @Html.ActionLink(name, "Details", "Students", new  id = UserDetailsId , null)
                    </td>
                    <td>
                        @Html.ActionLink(item.batch_code, "Details", "Batche", new  id = item.batch_code , null)
                    </td>
                    <td>
                        @Html.ActionLink(item.name, "Details", "Course", new  id = item.name , null)
                    </td>
                    <td>
                        @
                            var vendorname = CoursesTable.Where(x => x.name == item.name).Select(x => x.vendor_heading).FirstOrDefault();
                        
                        <label style="font-weight:normal !important">@vendorname</label>
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.adding_date)
                    </td>
                    <td style="width:100px;">
                        @using (Html.BeginForm())
                        
                            @Html.AntiForgeryToken()
                            @Html.HiddenFor(modelitem => item.id)

                            <div class="form-actions no-color">
                                <input type="submit" value="Confirm" class="btn btn-success" /> 
                            </div>
                        
                    </td>
                </tr>
                counter++;
            
        </table>
    </div>

循环内的渲染表单如下所示:

<form action="/Admin/ConfirmNewBatchRequest" method="post"> 
  <input name="__RequestVerificationToken" type="hidden" value="K4GmhPUCkcqqclPtxW7F1YpiT_6mQBBZu7Wi8JtfQDMWdmCPMQsbj‌​Bfmtr9t8pSBrOV6Yixhh‌​tz0B-OfMtxj4Y8dOwrdR‌​BXlz9v0sD7O8YE1" />
  <input data-val="true" data-val-number="The field id must be a number." data-val-required="The id field is required." id="item_id" name="item.id" type="hidden" value="3" /> 
  <div class="form-actions no-color"> 
    <input type="submit" value="Confirm" class="btn btn-success" /> 
  </div> 
</form>

这是我的模型如何与视图绑定 =>

public class Studentassignbatche

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int id  get; set; 
    /// <summary>
    /// ////////
    /// </summary>
    [Required(AllowEmptyStrings = false, ErrorMessage = "User Id Is Required!")]
    [MaxLength(12, ErrorMessage = "The Max length Of User ID is 12 Character!")]
    [RegularExpression("[1-3]2-[0-9]5-[123]1|[1-3]2-[0-9]7-[123]1", ErrorMessage = "Invalid Id,It should [xx]-[xxxxx]-[x] or [xx]-[xxxxxxx]-[x]!")]
    [Display(Name = "User ID")]
    public string UserId  get; set; 
    /// <summary>
    /// /////////
    /// </summary>
    [Required(AllowEmptyStrings = false, ErrorMessage = "Course Name Is Required!")]
    [MaxLength(700, ErrorMessage = "The Max Length For Course Name Is 700 Character!")]
    [Display(Name = "Course Name")]
    public string name  get; set; 
    /// <summary>
    /// /////////
    /// </summary>
    [Required(AllowEmptyStrings = false, ErrorMessage = "Batch Code Is Required!")]
    [MaxLength(700, ErrorMessage = "The Max Length For Batch Code Is 700 Character!")]
    [Display(Name = "Batch Code")]
    public string batch_code  get; set; 
    /// <summary>
    /// ///////
    /// </summary>
    [Required(AllowEmptyStrings = false, ErrorMessage = "Status Is Required!")]
    [RegularExpression("^(?:complete|Complete|in progress|In progress)$", ErrorMessage = "Invalid Status!")]
    [Display(Name = "Current Status")]
    public string status  get; set; 
    /// <summary>
    /// ////////
    /// </summary>
    [Display(Name = "Course Completion Date")]
    [DataType(DataType.DateTime,ErrorMessage="Invalid Date!")]
    public Nullable<DateTime> completion_date  get; set; 

    [Display(Name="Date Of Addition")]
    [DataType(DataType.DateTime,ErrorMessage="Invalid Date!")]
    public DateTime adding_date  get; set; 
    /// <summary>
    /// /////////
    /// </summary>
    [RegularExpression("^[01]1$", ErrorMessage = "Invalid Status Code!")]
    [Required(ErrorMessage="Status Code Is Required!")]
    public int StatusCode  get; set; 

    //relationship with anothere  table------

    [ForeignKey("UserId")]
    public User User  get; set; 
    /// <summary>
    /// //////
    /// </summary>
    [ForeignKey("name")]
    public Course Course  get; set; 
    /// <summary>
    /// ///////
    /// </summary>
    [ForeignKey("batch_code")]
    public Batche Batche  get; set; 

当我在控制器上调试时我发现 => 我尝试使用 =>

    public ActionResult ConfirmNewBatchRequest(Studentassignbatche Studentassignbatche)
    
        if (Studentassignbatche == null)
        
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        
    

但在首次亮相时,它仍然向我显示一个空对象。

为什么会发生这种情况,因为在视图方面它可以生成多个&lt;form&gt;&lt;/form&gt;。但据我所知,如果视图生成多个&lt;form&gt;&lt;/form&gt;,仍然每个表单都会获得一个隐藏的输入字段。 当表单提交时,它将与&lt;form&gt; 关联的特定隐藏字段。或者我的 URL 看起来像 http://localhost:43847/Admin/ConfirmNewBatchRequest 的一件事是 URL 有什么问题吗?那么为什么会出现这个问题,以及如何解决这个问题。

【问题讨论】:

呈现的 HTML 是什么样的?您创建的 Hidden 字段是否包含正确的 ID? @ADyson html 看起来像==> &lt;form action="/Admin/ConfirmNewBatchRequest" method="post"&gt; &lt;input name="__RequestVerificationToken" type="hidden" value="K4GmhPUCkcqqclPtxW7F1YpiT_6mQBBZu7Wi8JtfQDMWdmCPMQsbjBfmtr9t8pSBrOV6Yixhhtz0B-OfMtxj4Y8dOwrdRBXlz9v0sD7O8YE1" /&gt;&lt;input data-val="true" data-val-number="The field id must be a number." data-val-required="The id field is required." id="item_id" name="item.id" type="hidden" value="3" /&gt; &lt;div class="form-actions no-color"&gt; &lt;input type="submit" value="Confirm" class="btn btn-success" /&gt; &lt;/div&gt; &lt;/form&gt; 【参考方案1】:

问题是你的表单和你的回发方法不匹配。

在您的表单中,呈现的隐藏字段的nameitem.id。但是,您的操作方法只需要一个名为 id 的 int。该表单将提交它,就好像id 是一个名为item 的对象的一部分。

您用来呈现该字段的 HTML 助手是为您想要回发整个模型而设计的,而不仅仅是一个字段 - 即在这种情况下,您的操作方法必须接受 Studentassignbatche 类型的对象.

要解决此问题,您可以使用更简单的 HiddenField 助手版本:

@Html.Hidden("id", item.id)

这应该呈现如下内容:

<input name="id" type="hidden" value="3" />

这意味着name 与您的操作方法所期望的名称相匹配。

【讨论】:

以上是关于无法将数据从视图发送到控制器 Action .NET MVC的主要内容,如果未能解决你的问题,请参考以下文章

无法使用 Jquery 将数据从视图发送到控制器 Asp.net MVC

如何使用ajax将数据从视图发送到控制器laravel?

将 JSON 从视图发送到控制器 ASP.NET MVC 会给出空值

将数据从视图控制器发送到另一个

如何从视图控制器发送数据以在 swift 5 中嵌入视图控制器?

Url.Action:如何将参数从视图传递到控制器?