C# 已选择mvc发布下拉列表

C# 已选择mvc发布下拉列表,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,晚上好, 我在将所选值从视图传递到控制器时遇到了一些问题。我不明白我需要如何传递值,我一直在搜索信息,但没有结果。这是我的密码 控制器[获取] [HttpGet] public ActionResult AddProduct() { ideaworktelekrik.Models.ProductModel newProduct = new Models.ProductModel(); newProduct.Categories =

晚上好,

我在将所选值从视图传递到控制器时遇到了一些问题。我不明白我需要如何传递值,我一直在搜索信息,但没有结果。这是我的密码

控制器[获取]

            [HttpGet]
    public ActionResult AddProduct()
    {
      ideaworktelekrik.Models.ProductModel newProduct = new Models.ProductModel();
      newProduct.Categories = new SelectList( (from a in dbContext.Categories select new SelectListItem { Text = a.Category1, Value = a.ID.ToString()  }),"Value","Text");

        return View(newProduct);
    }
视图:

如果可能的话,请让我知道流程背后的逻辑,因为这个问题的主要目标是了解值是如何传递的(让它工作)

为了让您知道这个项目是关于什么的,这是一个添加产品页面,用户有两个文本框来输入产品信息,最后选择产品的类别(下拉列表),从而选择模型中的其他变量


谢谢大家。

当您创建选择列表时,您需要告诉它所选的值,请参见以下内容:

  newProduct.Categories = new SelectList( items: (from a in dbContext.Categories select new SelectListItem { Text = a.Category1, Value = a.ID.ToString() })
                                                selectedValue: newProduct.c_ID)
                                                , "Value", "Text");
这是为了在执行get时设置它。如果您对post有问题,您是否可以设置表单和控制器post方法(我假设它将在发布时填充模型上的c_ID)

我在将所选值传递给控制器时遇到了一些问题 在我看来

如果看不到模型属性,代码的简单版本将是:

@using (Html.BeginForm())
{
  <div class="form-group">
    @Html.DropDownListFor(model => model.c_ID, Model.Categories)
  </div>

  // any other form fields here

  <p>
    <input type="submit" value="Submit" />
  </p>
}
[HttpPost]
public ActionResult AddProduct(ProductModel model)
{
    // process your model data here
}

谢谢你的回答,基本上我对MVC的工作原理有错误的理解

我是在Get actionMethod中填充selectList,而不是在Post actionMethod中,因此在执行Post时,dropdownlist的参数为空

我在创建selectList时也有一些错误的逻辑(谢谢@Eric)和我的观点(谢谢@Eckert)


谢谢大家

我当前的系统完全按照您的建议设置,仍然返回null。@Eric Matson表示歉意,但您的代码中缺少括号或其他内容,1)通过“返回null”,您的意思是从表单发送的数据为null吗?2) 您确定您的下拉列表中有数值,而不仅仅是类别的文本吗?3) 如果将帮助器更改为松散类型(@DropDownList(“ID”,Model.Categories”),会发生什么情况?嘿,我刚刚发现了我的问题,我没有在帖子中返回模型。我添加了这个新产品。Categories=new SelectList((从数据库上下文中的中。Categories select new SelectList项目){Text=a.Category1,Value=a.ID.ToString()}),“Value”,“Text”,selectedValue:newProduct.c_ID);发布时仍返回null
@using (Html.BeginForm())
{
  <div class="form-group">
    @Html.DropDownListFor(model => model.c_ID, Model.Categories)
  </div>

  // any other form fields here

  <p>
    <input type="submit" value="Submit" />
  </p>
}
[HttpPost]
public ActionResult AddProduct(ProductModel model)
{
    // process your model data here
}