asp.net-mvc - 将 id 从 View 传递给 Controller

标签 asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

其实我是MVC的初学者。和简单的问题:

例如,我有类别页面的 ViewModel:

public class CategoryViewModel
{
    public int ProductId {get;set;}
    public int CategoryId {get;set;}
    public string ProductName {get;set;}
    public string CategoryName {get;set;}
}

在 Controller 中,我只是将 CategoryIdCategoryName 传递给 View :
public ActionResult Index()
{
    CategoryViewModel categoryViewModel = new CategoryViewModel();
    categoryViewModel.CategoryId = catId; \\Get from DB
    categoryViewModel.CategoryName = catName; \\Get from DB

    return View("Category", categoryViewModel);
}

然后在 View 上我需要将产品添加到这个类别:
<form action=@Url.Action("AddProduct", "Category") method="POST" enctype = "multipart/form-data">
    <textarea name ="ProductName"></textarea>
    <input type="submit" value="Add"/>
</form>

在 AddProduct 的 Controller 中:
[HttPost]
public ActionResult AddPost(CategoryViewModel categoryViewModel)
{
    var productName = categoryViewModel.ProductName;
    var categoryId = ?
    ProductRepository.AddProductToCategory(productName, categoryId);

    return new EmptyResult();
}

问题:如何获取 CategoryId ?或者也许还有另一种方法?

最佳答案

更改您的 View 以包含 CategoryId 属性的控件

@model CategoryViewModel
@using(Html.BeginForm("AddProduct", "Category"))
{
  @Html.HiddenFor(m => m.CategoryId)
  @Html.TextAreaFor(m => m.ProductName)
  <input type="submit" value="Add" />
}

请注意,始终使用强类型 html 助手来生成您的 html。

关于asp.net-mvc - 将 id 从 View 传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27452727/

相关文章:

c# - 名为 'MS_attributerouteWebApi' 的路由已经在路由集合中

javascript - Jquery上下文菜单ajax获取菜单项

asp.net - 在 Azure 上预热站点之前不要处理请求

c# - 如何在 Action 期间绑定(bind)模型?

asp.net-mvc-3 - 使用 asp mvc 3、nhibernate 3.2 和 spring.net 1.3.2 没有 Hibernate Session 绑定(bind)到线程异常

javascript - MVC - 有没有一种很好的方法可以将控件与其各自的 javascript 捆绑在一起?

c# - 在 MVC/C# 中创建 CSV 文件并通过 FTP 上传到服务器

c# - HtmlTargetElement 属性中的 Attributes 属性有何用途

asp.net-mvc-3 - 如何将MiniProfiler与单页Web应用程序/REST后端一起使用?

jquery - 使用 Ajax 结果填充 Kendo 网格