Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc mvc提交后ActionResult方法中无数据_Asp.net Mvc_Asp.net Mvc 3_Asp.net Mvc 4_Model View Controller - Fatal编程技术网

Asp.net mvc mvc提交后ActionResult方法中无数据

Asp.net mvc mvc提交后ActionResult方法中无数据,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-4,model-view-controller,Asp.net Mvc,Asp.net Mvc 3,Asp.net Mvc 4,Model View Controller,我有一个索引页面,上面有一个部分可以写项目名称并从下拉列表中选择项目类型 下面我有一个提交按钮,它指向项目控制器中创建的ActionResult方法 代码: [更新] index.cshtml: @using reqcoll.ViewModels @model myViewModel @{ ViewBag.Title = "ReqColl - project"; } @* First half *@ @using (Html.BeginForm("CreateProject", "Pro

我有一个索引页面,上面有一个部分可以写项目名称并从下拉列表中选择项目类型

下面我有一个提交按钮,它指向项目控制器中创建的ActionResult方法

代码: [更新] index.cshtml:

@using reqcoll.ViewModels
@model myViewModel

@{
  ViewBag.Title = "ReqColl - project";
}

@* First half *@
@using (Html.BeginForm("CreateProject", "Projects"))
{
  @Html.AntiForgeryToken()

  <div class="top-spacing col-md-12 col-lg-12 col-sm-12">
    @RenderTopHalf(Model.modelProject)
  </div>
}


@* Second half *@
@using (Html.BeginForm("CreateRequirement", "Projects"))
{
  @Html.AntiForgeryToken()

  <div class="form-group" id="pnSecondHalf">
    @* Requirements list *@
    <div class=" col-md-6 col-lg-6 col-sm-12">
      @RenderBottomLeftHalf(Model.modelRequirement)
    </div>

    @* New/Edit requirements panel *@
    <div class="col-md-6 col-lg-6 col-sm-12">
      @RenderBottomRightHalf(Model.modelRequirement)
    </div>
  </div>
}

@*     ================================================================================= ============= *@
@* Helpers *@

@helper RenderTopHalf(reqcoll.Models.Project project)
    {
  <div class=" well">
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="row">
      @Html.LabelFor(model => project.projectName, htmlAttributes: new { @class =     "control-label col-md-2 col-lg-2 col-sm-12" })
      <div class="col-md-10 col-lg-10 col-sm-12">
        @Html.TextBoxFor(model => project.projectName, htmlAttributes: new {   @class = "ProjectNameInput" })
        @Html.ValidationMessageFor(model => project.projectName)
      </div>
    </div>
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="row row-spacing">
      @Html.LabelFor(model => project.projectType, htmlAttributes: new { @class = "control-label col-md-2 col-lg-2 col-sm-12" })
      <div class="col-md-10 col-lg-10 col-sm-12">
        @Html.DropDownListFor(model => project.projectType, new SelectList(
              new List<Object>{
                       new { value = 0 , text = "...Select..." },
                       new { value = 1 , text = "Windows application" },
                       new { value = 2 , text = "Web application" },
                       new { value = 3 , text = "Device application"}
                },
              "value",
              "text",
               project.projectType), htmlAttributes: new { @class =    "DropDownList" })
        @Html.ValidationMessageFor(model => project.projectType)
      </div>
      <input type="hidden" value="" id="hdProjectID" />
    </div>
    <div class="row top-spacing col-md-offset-5 col-sm-offset-5">
      <div id="pnCreate" class=" col-sm-4 col-md-4 col-lg-4">
        <input type="submit" class="btn btn-default" value="Create" />
      </div>
      <div id="pnEdit" class=" col-sm-4 col-md-4 col-lg-4">
        <input type="submit" class="btn btn-default" value="Edit" />
        |
        <input type="submit" class="btn btn-default" value="Delete" />
      </div>
    </div>
  </div>
}

@helper RenderBottomLeftHalf(reqcoll.Models.Requirement requirement)
    {
  <div class=" well">
    <table class="table">
      <tr>
        <th>
          @if (Model.modelProject.Requirements != null)
          {
            var m = Model.modelProject;
            if (m.Requirements.Count > 0)
            {
              @Html.DisplayNameFor(model =>  model.modelProject.Requirements[0].shortDesc)
            }
          }
          else
          {
            <label class="label label-primary col-sm-12 col-md-6 col-lg-6">No requirements available</label>
          }
        </th>
        <th></th>
      </tr>
      @if (Model.modelProject.Requirements != null)
      {
        var m = Model.modelProject;
        if (m.Requirements.Count > 0)
        {
          foreach (var item in Model.modelProject.Requirements)
          {
            <tr>
              <td>
                @Html.DisplayFor(modelItem => item.shortDesc)
              </td>
              <td>

                @* buttons here*@

                @*@Html.ActionLink("E", "Edit", new { id = item.requirementID })     |
                  @Html.ActionLink("D", "Delete", new { id = item.requirementID     })*@
              </td>
            </tr>
          }
        }
      }
    </table>
  </div>
}



 @helper RenderBottomRightHalf(reqcoll.Models.Requirement requirement)
    {
  <div class=" well">
    @Html.ValidationSummary(true)
    <div class="row">
      @Html.LabelFor(model => requirement.shortDesc, htmlAttributes: new { @class = "control-label col-md-4 col-lg-4 col-sm-12" })
      <div class="col-md-8 col-lg-8 col-sm-12">
        @Html.TextBoxFor(model => requirement.shortDesc, htmlAttributes: new { @class = "RequirementShortDesc" })
        @Html.ValidationMessageFor(model => requirement.shortDesc)
      </div>
    </div>
    @Html.ValidationSummary(true)
    <div class="row row-spacing">
      @Html.LabelFor(model => requirement.longDesc, htmlAttributes: new { @class = "control-label col-md-4 col-lg-4 col-sm-12" })
      <div class="col-md-8 col-lg-8 col-sm-12 RequirementLongDesc">
        @Html.EditorFor(model => requirement.longDesc)
        @Html.ValidationMessageFor(model => requirement.longDesc)
      </div>
    </div>
    @Html.ValidationSummary(true)
    <div class="row row-spacing">
      @Html.LabelFor(model => requirement.priorityCode, htmlAttributes: new { @class = "control-label col-md-4 col-lg-4 col-sm-12" })
      <div class="col-md-8 col-lg-8 col-sm-12">

        @foreach (var value in Enum.GetValues(requirement.priorityCode.GetType()))
        {
          <div class="control-label col-sm-5 col-md-5 col-lg-5">
            @Html.RadioButtonFor(m => requirement.priorityCode, value)
            @Html.Label(value.ToString())
          </div>
        }


        @Html.ValidationMessageFor(model => requirement.priorityCode)
      </div>
    </div>
    <input type="hidden" value="" id="hdRequirementID" />

    <div class="row top-spacing col-md-offset-5 col-sm-offset-5">
      <div id="pnReqCreate" class=" col-sm-12 col-md-6 col-lg-6">

        @* submit button here *@
        @*@Html.ActionLink("Add", "Add", "Requirement", new { @class = "btn btn-default btnSize" })*@
      </div>
      <div id="pnReqEdit" class=" col-sm-12 col-md-6 col-lg-6">
        @* submit buttons here *@
        @*@Html.ActionLink("Edit", "Edit", "Requirement", new { @class = "btn btn-default btnSize" })
          @Html.ActionLink("Delete", "Delete", "Requirement", new { @class = "btn btn-default btnSize" })*@
      </div>
    </div>
  </div>
}





@section Scripts {
  <script>

    $(function () {

      var pID = $('#hdProjectID').val();

      if (pID != null) {
        if (pID.length > 0) {
          $('#pnEdit').show();
          $('#pnCreate').hide();
          $('#pnSecondHalf').show();
        } else {
          $('#pnEdit').hide();
          $('#pnCreate').show();
          $('#pnSecondHalf').hide();
        }
      } else {
        $('#pnEdit').hide();
        $('#pnCreate').show();
        $('#pnSecondHalf').hide();
      }

      var rID = $('#hdRequirementID').val();

      if (rID != null) {
        if (rID.length > 0) {
          $('#pnReqEdit').show();
          $('#pnReqCreate').hide();
        } else {
          $('#pnReqEdit').hide();
          $('#pnReqCreate').show();
        }
      } else {
        $('#pnReqEdit').hide();
        $('#pnReqCreate').show();
      }

    });

  </script>

  @Scripts.Render("~/bundles/jqueryval")
}
控制器:

using System.Web.Mvc;
using reqcoll.Models;
using reqcoll.ViewModels;

namespace reqcoll.Controllers
{
  public class ProjectsController : Controller
  {
    private myContext db = new myContext();

    // GET: Projects
    public ActionResult Index()
    {
      // allow more than one model to be used in the view

      var vm = new myViewModel()
      {
        modelProject = new Project() { projectName = "test", projectType = 1 },
        modelRequirement = new Requirement() { requirementID = -1 },
      };

      return View(vm);
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult CreateProject(myViewModel vm)
    {
      if (vm != null)
      {
        var ab = Request.Form;

        // key 1: __RequestVerificationToken
        // key 2: project.projectName
        // key 3: project.projectType


        if (ModelState.IsValid)
        {
          Project project = vm.modelProject;

          // db.Project.Add(project.Item1);
          //  db.SaveChanges();
          // return RedirectToAction("Index");
        }
      }
      return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
      if (disposing)
      {
        db.Dispose();
      }
      base.Dispose(disposing);
    }

  }
}
 private myContext db = new myContext();

 // GET: Projects
 public ActionResult Index()
 {
   // allow more than one model to be used in the view
   return View(new Tuple<Project, Requirement, Priority>(new Project(), new Requirement(), new Priority()));
 }

 [HttpPost]
 [ValidateAntiForgeryToken]
 [AcceptVerbs(HttpVerbs.Post)]
 public ActionResult Create([Bind(Include = "projectName,projectType")] Project project)
 {
   if (ModelState.IsValid)
   {
     db.Project.Add(project);
     db.SaveChanges();
     return RedirectToAction("Index");
   }

   return RedirectToAction("Index");
 }
[原件]

@using (Html.BeginForm("Create", "Projects"))
{
  @Html.AntiForgeryToken()

  <div class="top-spacing col-md-12 col-lg-12 col-sm-12">
    <div class=" well">
      @Html.ValidationSummary(true)
      <div class="row">
        @Html.LabelFor(model => model.Item1.projectName, htmlAttributes: new { @class = "control-label col-md-2 col-lg-2 col-sm-12" })
        <div class="col-md-10 col-lg-10 col-sm-12">
          @Html.TextBoxFor(model => model.Item1.projectName, htmlAttributes: new { @class = "ProjectNameInput" })
          @Html.ValidationMessageFor(model => model.Item1.projectName)
        </div>
      </div>
      @Html.ValidationSummary(true)
      <div class="row row-spacing">
        @Html.LabelFor(model => model.Item1.projectType, htmlAttributes: new { @class = "control-label col-md-2 col-lg-2 col-sm-12" })
        <div class="col-md-10 col-lg-10 col-sm-12">
          @Html.DropDownListFor(model => model.Item1.projectType, new  SelectList(
              new List<Object>{
                       new { value = 0 , text = "...Select..."  },
                       new { value = 1 , text = "Windows application"  },
                       new { value = 2 , text = "Web application" },
                       new { value = 3 , text = "Device application"}
                },
              "value",
              "text",
               0), htmlAttributes: new { @class = "DropDownList" })
          @Html.ValidationMessageFor(model => model.Item1.projectType)
        </div>
        <input type="hidden" value="" id="hdProjectID" />
      </div>
      <div class="row top-spacing col-md-offset-5 col-sm-offset-5">
        <div id="pnCreate" class=" col-sm-4 col-md-4 col-lg-4">
          <input type="submit" class="btn btn-default" value="Create" />
        </div>
        <div id="pnEdit" class=" col-sm-4 col-md-4 col-lg-4">

          <input type="submit" class="btn btn-default" value="Edit" />
          |
          <input type="submit" class="btn btn-default" value="Delete" />
        </div>
      </div>
    </div>
  </div>
}
使用(Html.BeginForm(“创建”、“项目”)) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) @LabelFor(model=>model.Item1.projectName,htmlAttributes:new{@class=“control label col-md-2 col-lg-2 col-sm-12”}) @TextBoxFor(model=>model.Item1.projectName,htmlAttributes:new{@class=“ProjectNameInput”}) @Html.ValidationMessageFor(model=>model.Item1.projectName) @Html.ValidationSummary(true) @LabelFor(model=>model.Item1.projectType,htmlAttributes:new{@class=“controllabel col-md-2 col-lg-2 col-sm-12”}) @DropDownListFor(model=>model.Item1.projectType,新选择列表( 新名单{ 新建{value=0,text=“…选择…”, 新建{value=1,text=“Windows应用程序”}, 新建{value=2,text=“Web应用程序”}, 新建{value=3,text=“设备应用程序”} }, “价值”, “文本”, 0),htmlAttributes:new{@class=“DropDownList”}) @Html.ValidationMessageFor(model=>model.Item1.projectType) | } 项目控制器:

using System.Web.Mvc;
using reqcoll.Models;
using reqcoll.ViewModels;

namespace reqcoll.Controllers
{
  public class ProjectsController : Controller
  {
    private myContext db = new myContext();

    // GET: Projects
    public ActionResult Index()
    {
      // allow more than one model to be used in the view

      var vm = new myViewModel()
      {
        modelProject = new Project() { projectName = "test", projectType = 1 },
        modelRequirement = new Requirement() { requirementID = -1 },
      };

      return View(vm);
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult CreateProject(myViewModel vm)
    {
      if (vm != null)
      {
        var ab = Request.Form;

        // key 1: __RequestVerificationToken
        // key 2: project.projectName
        // key 3: project.projectType


        if (ModelState.IsValid)
        {
          Project project = vm.modelProject;

          // db.Project.Add(project.Item1);
          //  db.SaveChanges();
          // return RedirectToAction("Index");
        }
      }
      return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
      if (disposing)
      {
        db.Dispose();
      }
      base.Dispose(disposing);
    }

  }
}
 private myContext db = new myContext();

 // GET: Projects
 public ActionResult Index()
 {
   // allow more than one model to be used in the view
   return View(new Tuple<Project, Requirement, Priority>(new Project(), new Requirement(), new Priority()));
 }

 [HttpPost]
 [ValidateAntiForgeryToken]
 [AcceptVerbs(HttpVerbs.Post)]
 public ActionResult Create([Bind(Include = "projectName,projectType")] Project project)
 {
   if (ModelState.IsValid)
   {
     db.Project.Add(project);
     db.SaveChanges();
     return RedirectToAction("Index");
   }

   return RedirectToAction("Index");
 }
private myContext db=new myContext();
//获取:项目
公共行动结果索引()
{
//允许在视图中使用多个模型
返回视图(新元组(新项目(),新需求(),新优先级());
}
[HttpPost]
[ValidateAntiForgeryToken]
[接受动词(HttpVerbs.Post)]
公共操作结果创建([Bind(Include=“projectName,projectType”)]项目)
{
if(ModelState.IsValid)
{
db.Project.Add(项目);
db.SaveChanges();
返回操作(“索引”);
}
返回操作(“索引”);
}
因此,当单击submit按钮时,将调用ActionResult创建,但是ModelState无效,并且没有用户输入的信息


我做错了什么?

当您使用model.Item1.projectName和model.Item1.projectType时,您的模型看起来像一个复杂的对象,但在action方法中,您试图直接获取值,这是错误的。

[更新的代码]

发布新代码后,此模型的快速更正将允许它从您的视图中正确绑定:

namespace reqcoll.ViewModels
{
  public class myViewModel
  {
    public Project project;
    public Requirement requirement;

  }
}
[原件]

尽管使用了元组类型,而不是定义一个类来封装要传递给视图的数据。您仍然可以通过在视图中创建辅助对象来实现所需的功能

@helper RenderMyProject(Project project) {
    ...
    @Html.TextBoxFor(x=> project.projectType)
    ...
}
然后,您将调用此助手

@RenderMyProject(model.Item1)
有什么区别

输入的名称将更改。响应对象中的[Item1.projectType]不会发布到控制器,它看起来像[project.projectType],会自动映射到项目参数。

发现问题

我在myViewModel中向这两个模型添加了{get;set;},然后它就工作了

因此:


如果我只是改变了我的控件和视图来使用一个包含所有需要的模型的类?使用同一个助手?我现在有一个模型类。我使用了助手来简化代码。如果我运行该网站,并且在调用助手的行上设置了断点,我可以看到模型被传递给了助手。但在提交时,输入的信息不会发布。现在是单向交通,我需要双向交通。在你的控制器上设置一个断点。您应该能够检查对象[Request.Form]。键值应表示对象的属性。由于您的创建操作需要一个项目,因此响应键应该包含属性名称(如“projectType”)或参数+属性名称(如“Project.propertyName”),我看到3个键,一个不是我的,另外两个来自我的项目模型。但是没有值。在Request.Form对象中,我们应该看到三个键“_RequestVerificationToken”是您的反ForgeryToken•“Item1.projectName”•“Item1.projectType”您不能在绑定中使用复杂对象。所以,若要在绑定中访问,必须使用具有直接属性的视图模型,而不是复杂的视图模型。