Reputation: 969
i've a trouble, i need a webgrid with a form for each row, i achieved this, but when i click the submit button the controller don't recieve an input text.
This is the code for the view:
@grid.GetHtml(
tableStyle: "mGrid",
headerStyle: "head",
alternatingRowStyle: "alt",
rowStyle: "altRow",
columns: grid.Columns(
grid.Column(columnName: "Id", header: "Id", style: "prefix"),
grid.Column(columnName: "Trademark", header: "Marca", style: "trademark"),
grid.Column(columnName: "Price", header: "Precio", style: "price", format: @<text>@item.Price.ToString("N2")</text>),
grid.Column(format: (item) =>
{
System.Text.StringBuilder html = new System.Text.StringBuilder();
html.Append("<form action=\"/Cart/AddToCart\" method=\"get\">");
html.Append("<input type=\"text\" value=\"\" style=\"width:50px; text-align:center; \" name=\"quantity\" id=\"quantity\" />");
html.Append("<input type=\"submit\" value=\"Agregar\" class=\"btnAdd\" />");
html.Append("<input type=\"hidden\" name=\"productId\" value=\"" + item.Value.Id + "\"/>");
html.Append("<input type=\"hidden\" name=\"returnUrl\" value=\"" + Request.Url + "\"/>");
html.Append("</form>");
return new HtmlString(html.ToString());
}
)
)
)
And this is part of the controller:
public class CartController : Controller
{
private IDataRepository repository;
...
public RedirectToRouteResult AddToCart(Cart cart, int productId, int quantity, string returnURL)
{
Product product = repository.Products.FirstOrDefault(p => p.Id == productId);
if (product != null)
cart.AddItem(product, quantity);
return RedirectToAction("Index", new { returnURL });
}
Everything compile Ok. But when execute quantity always is null, i have already tried quantity as int and string with the same result.
Any help will be wellcome. Thanks.
Upvotes: 0
Views: 1986
Reputation: 7591
to start you can drop the URL argument and associated hidden field. use Request.Referrer to return to the previous action instead.
second, quantity cannot be null, it would either be zero or non-zero, but an integer cannot be null.
third, where is Cart coming from? If this is domain object, I would pass the id to the action and load the cart in the action. I would also combine the primatives into a context specific DTO.
AddToCart(AddToCartCommand input)
{
var cart = repository.Carts.First(input.CartId);
var product = repository.Products.First(input.ProductId);
cart.Add(product, input.Quantity);
return RedirectToAction(Request.Referrer);
}
where AddToCartCommand is
class AddToCartCommand
{
public int CartId {get;set;}
public int ProductId {get;set;}
public int Quantity {get;set;}
}
Upvotes: 1