.NET MVC C#错误 - 必须绑定数据源才能执行此操作

时间:2016-07-14 18:18:31

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

我遇到以下错误:

必须先绑定数据源才能执行此操作。

我有一个文本框,用户输入名称,然后单击提交按钮。该名称将添加到列表中。我已经研究了错误,但我尝试的一切都给了我同样的错误。任何有关我所做错事的见解都将受到赞赏。

型号:

namespace RangeTest.Models
{
    public class UserNameModel
    {
        [Key]
        public int Id { get; set; }
        [Display(Name = "Names Added List")]
        public string FullName { get; set; }    

     }

}

控制器:

   public ActionResult Admin()
    {


        return View();
    }


    [HttpPost]
    public ActionResult Admin(UserNameModel model, IEnumerable<RangeTest.Models.UserNameModel> t)
    {

        List<UserNameModel> userList = new List<UserNameModel>();
        model.FullName = t.FirstOrDefault().FullName;
        userList.Add(model);

        return View(userList.ToList());

    }

查看(Admin.cshtml):

@model IEnumerable<RangeTest.Models.UserNameModel>

@{
    ViewBag.Title = "";
 }
<div class="container"></div>
<div class="jumbotron">
@using (Html.BeginForm("Admin", "UserNames", FormMethod.Post, new { @id = "WebGridForm" }))
{
    @Html.ValidationSummary(true)


    WebGrid dataGrid = new WebGrid(Model, canPage: false, canSort: false);
    //Func<bool, MvcHtmlString> func =
    //(b) => b ? MvcHtmlString.Create("checked=\"checked\"") : MvcHtmlString.Empty;

    <div class="table-bordered">
        <div class="Title">Admin - Add names to range list</div><br />
        <table id="TblAdd"class="table">

            <tr>

                @{
                    RangeTest.Models.UserNameModel t = new RangeTest.Models.UserNameModel();
                }
                @Html.Partial("_AddDynTable", t)
        </table>
        </div>
        <div class="table-responsive">
            <div class="Title">Names Added to Range List</div>
                    <table class="table">

                        <tr>

                            <td >
                                @dataGrid.GetHtml(columns: dataGrid.Columns(dataGrid.Column(format: @<text>@item</text>),
                                       dataGrid.Column("", format: (item) => Html.ActionLink("Delete", "Delete", new { id = item.id }))))
                            </td>

                        </tr>
                    </table>
                </div>
}

    </div>

部分视图(_addDynTable.cshtml)

@model RangeTest.Models.UserNameModel


<tr>
    <td>
        Enter Full Name: @Html.TextBoxFor(m => m.FullName)
  @*<input type="button" value="Create" id="ClickToAdd" />*@<input class="CreateBtn" type="submit" value="Add to List" /></td>

</tr>     

1 个答案:

答案 0 :(得分:0)

您可以链接有关错误的信息吗?

我可以看到的一件事是,当你将t对象传递给局部视图

时,它是null

RangeTest.Models.UserNameModel t = new RangeTest.Models.UserNameModel();

新的UserNameModel,其中没有数据,如果您的错误可能存在问题