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

时间:2017-05-23 12:28:43

标签: c# asp.net asp.net-mvc forms asp.net-mvc-4

只需从View To Controller Action发送一个int数据。但是控制器动作没有接收到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>

以下是我的模型与view =&gt;

绑定的方式
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; }
}

在我调试的控制器上我发现了=&gt; enter image description here 我尝试使用=&gt;

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

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

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

1 个答案:

答案 0 :(得分:2)

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

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

您用于渲染字段的HTML帮助程序是为了在您想要回发整个模型时设计的,而不仅仅是一个字段 - 即在这种情况下,您的操作方法必须接受类型{{1 }}

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

Studentassignbatche

这应该像:

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

这意味着<input name="id" type="hidden" value="3" /> 与您的操作方法所期望的名称相匹配。