Home > Blockchain >  BindProperty does not working for objects
BindProperty does not working for objects

Time:11-19

I have a form submission in place. I am binding four properties. One is a string, one is an integer, the other two are class objects. Here is my backend:

`       [BindProperty]
        public PortfolioModel Portfolio { get; set; }
        [BindProperty]
        public StockModel Stock { get; set; }
        [BindProperty]
        public string StockSymbol { get; set; }
        [BindProperty]
        public int QuantityToTrade { get; set; }`

These are all populated in OnGetAsync(). And they are correct during debug mode. Here is my frontend:

`        <form method="post">

        <div>
            Qty. <input type="text" name="QuantityToTrade" id="QuantityToTrade" /> 
            <input type="hidden" asp-for="@Model.StockSymbol" />
            <input type="hidden" asp-for="@Model.Stock" />
            <input type="hidden" asp-for="@Model.Portfolio" />
            <input  type="submit" value="Buy" asp-page-handler="Buy" />
            <input  type="submit" value="Sell" asp-page-handler="Sell" />
        </div>

        </form>`

When I submit the form:

`        public async Task<IActionResult> OnPostBuyAsync()
        {
            OrderModel orderPlaced = null;

            if (QuantityToTrade > 0)
            {
                OrderModel orderModel = new OrderModel()
                {
                    PortfolioId = Portfolio.Id,
                    StockId = Stock.Id,
                    StockSymbol = StockSymbol,
                    QuantityTraded = QuantityToTrade,

                };
             }
         }`

The problem is, in OnPostBuyAsync(), both StockSymbol and QuantityToTrade are correct. But Portfolio and Stock have all 0's for the integer fields, and null for all other fields. Why are the class objects not posted correctly?

The most common answer for this problem on stackoverflow, is that the property setter was set to private. But in my case, they are all public...

CodePudding user response:

Tag helper cannot bind the complex model with single input. You need specify all the property you want get in complex model.

For your scenario, it should be:

<div>
    Qty. <input type="text" name="QuantityToTrade" id="QuantityToTrade" />
    <input type="hidden" asp-for="@Model.StockSymbol" />
    <input type="hidden" asp-for="@Model.Stock.Id" />    //specify the property
    <input type="hidden" asp-for="@Model.Portfolio.Id" />     //specify the property
    <input  type="submit" value="Buy" asp-page-handler="Buy" />
    <input  type="submit" value="Sell" asp-page-handler="Sell" />
</div>
  • Related