I am new to .NET and bad at English. This is the code for my form. Currently, I am only getting the value for productName but I need to get the value for "category" too. "category" remains to be Null when the controller is called. What am I doing wrong? Can anyone give me a hint here?
<form asp-controller="Products" asp-action="ByCategory" method="get">
<div style="margin: 4px 10px 12px 1px">
<div mt-2>
<input type="text" name="productName" placeholder="Serch by name" />
<div >
<input type="submit" value="Search" />
</div>
<button type="button" name="category"
id="category" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"
style="margin: 0px 0px 0px 10px">
Categories
</button>
<div aria-labelledby="">
@for (int i = 0; i <= 2; i )
{
<button type="button">@ViewBag.Data[i]</button>
}
</div>
</div>
</div>
</form>
``````
and here is the code for my controller
``````
public async Task<IActionResult> ByCategory(string category, string productName)
{
var model = _context.Product.Where(p => p.Name.Equals(productName)).Select(p => new ProductViewModel
{
Id = p.Id,
Name = p.Name,
Price = p.Price,
Count = p.Count,
InventoryValue = p.Count * p.Price,
Category = p.Category
});
return View("ByCategory", await model.ToListAsync());
}
``````
CodePudding user response:
At the moment you have defined one input for your form
<input type="text" name="productName" placeholder="Serch by name" />
You should also define a second input for category
so that it will also be submitted with the form.
CodePudding user response:
1.Form submit cannot automatically post the button value. You need set a hidden input and use jQuery to set the input value when you choose the dropdownlist.
2.Model Binding binds the property by name attribute. You need set name="category"
for the hidden input.
Here is a whole working demo:
<form asp-controller="Products" asp-action="ByCategory" method="get">
<div style="margin: 4px 10px 12px 1px">
<div mt-2>
<input type="text" name="productName" placeholder="Serch by name" />
//add hidden input here..
<input type="text" name="category" id="category" hidden>
<div >
<input type="submit" value="Search" />
</div>
<button type="button" name="category"
id="category" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"
style="margin: 0px 0px 0px 10px">
Categories
</button>
<div aria-labelledby="">
@for (int i = 0; i <= 2; i )
{
<button type="button">@ViewBag.Data[i]</button>
}
</div>
</div>
</div>
</form>
@section Scripts
{
<script>
$("button.dropdown-item").click(function(){
$("#category").val($(this).text());
})
</script>
}