Pass id from view to controller
I am actually new to MVC. And a simple question:
For example, I have a ViewModel for a Category page:
public class CategoryViewModel
{
public int ProductId {get;set;}
public int CategoryId {get;set;}
public string ProductName {get;set;}
public string CategoryName {get;set;}
}
In the controller, I just pass CategoryId
it CategoryName
to the view too :
public ActionResult Index()
{
CategoryViewModel categoryViewModel = new CategoryViewModel();
categoryViewModel.CategoryId = catId; \\Get from DB
categoryViewModel.CategoryName = catName; \\Get from DB
return View("Category", categoryViewModel);
}
Then, in the view, I need to add a Product to this category:
<form action=@Url.Action("AddProduct", "Category") method="POST" enctype = "multipart/form-data">
<textarea name ="ProductName"></textarea>
<input type="submit" value="Add"/>
</form>
And in the AddProduct controller:
[HttPost]
public ActionResult AddPost(CategoryViewModel categoryViewModel)
{
var productName = categoryViewModel.ProductName;
var categoryId = ?
ProductRepository.AddProductToCategory(productName, categoryId);
return new EmptyResult();
}
Question: How to get it CategoryId
? Or maybe there is another approach?
source to share
Change your view to include a control for the property CategoryId
@model CategoryViewModel
@using(Html.BeginForm("AddProduct", "Category"))
{
@Html.HiddenFor(m => m.CategoryId)
@Html.TextAreaFor(m => m.ProductName)
<input type="submit" value="Add" />
}
Note, always use heavily the html helper types to generate your html.
source to share
thanks to Stephen Mukek
Also you can pass id from (form self) and other properties you want, but you must define the input method.
@model CategoryViewModel
@using (Html.BeginForm("AddProduct", "Category", new { id = Model.CategoryId }, FormMethod.Post, new { }))
{
@Html.TextAreaFor(m => m.ProductName)
<input type="submit" value="Add" />
}
Action method:
[HttPost]
public ActionResult AddPost(CategoryViewModel categoryViewModel,int id)
{
var productName = categoryViewModel.ProductName;
var categoryId = id
ProductRepository.AddProductToCategory(productName, categoryId);
return new EmptyResult();
}
Hope this helps you.
source to share