选择mvc发布下拉列表

时间:2015-05-06 15:45:30

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

晚上好,

从我的View中将所选值传递给控制器​​时遇到了一些麻烦。我不明白我需要如何传递价值,我一直在寻找无济于事的信息。这是我的代码

控制器[GET]

            [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);
    }

查看:

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

型号:

            public string Name {get;set;}
    public int c_ID { get; set; }
    public Guid _ID {get;set;} 
    public string imageurl {get;set;}
    public SelectList Categories {get;set;}
    public string CategorySelected { get; set; }

如果有可能,请让我知道这个过程背后的逻辑,因为这个问题的主要目标是学习如何传递价值观(让他们开始工作)。

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

谢谢你们。

3 个答案:

答案 0 :(得分:0)

创建选择列表时,需要告诉它所选的值,见下文:

  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时设置它,如果你对帖子有问题,你可以提出你的表单和控制器发布方法,(我假设它会在模型​​时填充模型上的c_ID)发布)。

答案 1 :(得分:0)

  

将选定值传递给控制器​​时遇到了一些麻烦   从我的观点。

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

@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
}

答案 2 :(得分:0)

感谢您的回答,基本上我对MVC的运作方式有了错误的理解。

我在Get actionMethod中填充selectList而不是在post actionMethod中填充,因此当帖子被执行时,它是下拉列表中的空参数。

我的selectList创建中也有一些错误的逻辑(感谢@Eric)以及我的视图(感谢@Eckert)

谢谢你们!

相关问题