基于从另一个表单MVC 4上的链接传递的输入将记录添加到数据库

时间:2014-06-11 09:40:32

标签: asp.net-mvc-4

我一直在使用ASP.NET MVC 4但我还没有遇到过这样的情况:我需要从一个基于从另一个视图传递的值的脚手架Create视图向数据库中插入一个值。我试图从编辑视图推断尝试修改我的代码工作,但我遇到了障碍。我收到类似于post的错误。这是我传递值

的视图中的代码
 @Html.ActionLink("Allocate", "Create", "Allocation", new { id=item.requestID}, null)

这是来自索引视图

中数据库中已有的请求列表

这是我的控制器上的代码,它试图强制Create方法使用从上面的链接传递的ID

public ActionResult Create(int id = 0)
{
Request request = db.Requests.Find(id);
        ViewBag.requestID = new SelectList(db.Requests, "requestID", "requestID", request.requestID);
        return View(request);
}

然后这是db

的发布代码
[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Allocation allocation)
    {
        if (ModelState.IsValid)
        {
            db.Allocations.Add(allocation);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.requestID = new SelectList(db.Requests, "requestID", "requestID", allocation.requestID);
        return View(allocation);
    }

基本上我要做的是将资金分配给根据请求ID将分配输入数据库的请求。我试图阻止用户从下拉列表中选择请求ID。当我运行这个时我得到一个错误

The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.Request_A52006F7570E0448EE323CB36858E4D13EED0BAD958340B32FF166708545DA8C', but this dictionary requires a model item of type 'BudgetAllocation.Models.Allocation'.

如果有人可以帮我解决这个问题,请尽快做。我很欣赏所有的努力!!!!!

// EDIT 这是我的创建视图

@model BudgetAllocation.Models.Allocation

@{
ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<fieldset>
    <legend>Allocation</legend>
    @Html.HiddenFor(model => model.requestID)

    <div class="editor-label">
        @Html.LabelFor(model => model.allocAmount, "Amount")
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.allocAmount)
        @Html.ValidationMessageFor(model => model.allocAmount)
    </div>

    <p>
        <input type="submit" value="Allocate" />
    </p>
</fieldset>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}

1 个答案:

答案 0 :(得分:0)

问题是您的视图ID 强类型BudgetAllocation.Models.AllocationCreate的获取操作中您传递的类型为BudgetAllocation.Models.Request的对象,这就是您获得的原因例外。

你必须在Create get动作中传递BudgetAllocation.Models.Allocation类型的对象,因为你的视图是强类型的。

public ActionResult Create(int id = 0)
{
Request request = db.Requests.Find(id);

return View(request) // <-------------- here is the mistake

}

它应该返回分配对象,就像这样,它只是一个例子,你可能需要做一些其他事情而不是选择:

public ActionResult Create(int id = 0)
{
Allocation allocation = db.Allocations.Find(x=>x.requestID == id);
ViewBag.requestID = new SelectList(db.Requests, "requestID", "requestID", request.requestID);
return View(allocation);
}

<强>更新

你只需要这样做就不要返回allocaiton对象返回简单的视图:

public ActionResult Create(int id = 0)
    {
    ViewBag.requestID = new SelectList(db.Requests, "requestID", "requestID", request.requestID);
    return View();
    }