简体   繁体   中英

Why HiddenFor get null value in post action method in MVC 5?

I have a partial view in whicn whenever i post the form, hiddenfor gets null value. When i add new one it gets null value but when i edit, it works fine. I check the error by using this code.

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();

Error says the id field is required. I am using @Html.HiddenFor(model => model.Id) the form is ajax.beginform What is the problem?

EDIT:

[HttpGet]
        public ActionResult ProductPartial(int Id = -1)
        {
            var ProductService = new ProductService();

            var Product = new Product();
            bool editMode = ProductId > 0;

            if (editMode)
            {
                var ProductId = Convert.ToInt32(ProductId);
                var entity = ProductService.GetByProductId(null, ProductId);
                Product.Id = entity.ProductId;
                Product.ProductName = entity.ProductName;

            }

            return PartialView(Product);
        }

        [HttpPost]
        public JsonResult ProductPartial(Product Product)
        {
           //Product id gets null
           //Perfome some action


            return Json(returnData);
        }
Product class
 public abstract class ProductBase
{
    public virtual int Id{set;get}
    public virtual string Name {set;get}

}

public class Product : ProductBase
{}

This works:

 // Controller
    [HttpPost]
    public ActionResult Send(BitcoinTransactionViewModel **RedeemTransaction**)
    {
    }

    // View
    @using (Html.BeginForm("Send", "DepositDetails", FormMethod.Post, new { **RedeemTransaction** = Model }))
    {

    @Html.HiddenFor(m => m.Token);
    @Html.HiddenFor(m => m.Transaction.TransactionId);
    .
    .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM