gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:30:46 25 4
gpt4 key购买 nike

其实我是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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com