locked
MVC problem about Html.BeginForm() RRS feed

  • Question

  • User-898349087 posted

    l want Edit ProductModel and Save,but have a problem.

    this is part of code.

    //the product model
        public class Product
        {
            [HiddenInput(DisplayValue =false)]
            public int ProductID { get; set; }
            [Required(ErrorMessage ="write name")]
            public string Name { get; set; }
            [DataType(DataType.MultilineText)]
            [Required(ErrorMessage = "write Description")]
            public string Description { get; set; }
            [Required]
            [Range(0.01,double.MaxValue,ErrorMessage ="write price")]
            public decimal Price { get; set; }
            [Required(ErrorMessage = "write Category")]
            public string Category { get; set; }
        }
    public class EFProductRepository : IProductsRepository
        {
            private EFDbContext context = new EFDbContext();
    
            public IEnumerable<Product> Products => context.Products;
    
            //Save the model
            public void SavePorduct(Product product)
            {
                if(product.ProductID==0)//if id==0 then add new product
                {
                    context.Products.Add(product);
                }
                else//else change and Save
                {
                    Product dbEntry = context.Products.Find(product.ProductID);
                    if(dbEntry!=null)
                    {
                        dbEntry.Name = product.Name;
                        dbEntry.Description = product.Description;
                        dbEntry.Price = product.Price;
                        dbEntry.Category = product.Category;
                    }
                }
                context.SaveChanges();
            }
        }
    //CRUD Controller
        public class AdminController : Controller
        {
            private IProductsRepository repository;
            public AdminController(IProductsRepository repo)
            {
                repository = repo;
            }
            // GET: Admin
            public ActionResult Index()
            {
                return View(repository.Products);
            }
    
            public ActionResult Edit(int productid)
            {
                Product product = repository.Products.FirstOrDefault(p => p.ProductID == productid);
                return View(product);
            }
    
            [HttpPost]
            public ActionResult Edit(Product product)
            {
                if (ModelState.IsValid)
                {
                    repository.SavePorduct(product);
                    TempData["message"] = string.Format("{0}has save", product.Name);
                    return RedirectToAction("Index");
                }
                else
                    return View(product);
            }
        }
    @model Store.Domain.Entities.Product
    @{//the EditView
        ViewBag.Title = "Edit";
        Layout = "~/Views/Shared/_AdminLayout.cshtml";
    }
    <div class="panel">
        <div class="panel-heading">
            <h3>Edit @Model.Name  @Model.ProductID</h3>
        </div>
    
        @using (Html.BeginForm("Edit","Admin"))<!--here is the problem-->
        {
            <div class="panel-body">
                @foreach (var property in ViewData.ModelMetadata.Properties)
                {
                    if (property.PropertyName != "ProductID")
                    {
                        <div class="form-group">
                            <label>@(property.DisplayName ?? property.PropertyName)</label>
                            @if (property.PropertyName == "Description")
                            {
                                @Html.TextArea(property.PropertyName, null,
                                    new { @class = "form-control", rows = 5 })
                            }
                            else
                            {
                                @Html.TextBox(property.PropertyName, null,
                                    new { @class = "form-control" })
                            }
                            @Html.ValidationMessage(property.PropertyName)
                        </div>
                    }
                }
            </div>
            <div class="panel-footer">
                <input type="submit" value="save" class="btn btn-primary" />
                @Html.ActionLink("cancel", "Index", null, new {
               @class = "btn btn-default"
           })
            </div>
        }
    </div>

     its the problem in the EditView if i use Html.BeginForm("Edit","Admin") it will auto change the Model's ProductID to 0 , and it will not Edit success.(l have not change the ProductID  by myself)

    But if i use Html.BeginForm() it will edit and save success.

    So how its happen?

    Did i have some wrong about code?

    If i use Html.BeginForm("Edit","Admin") how can i change my code?

    Wednesday, August 28, 2019 5:58 AM

Answers

  • User-1038772411 posted

    Hello,whiskets

    @Html.AntiForgeryToken()
    @Html.HiddenFor(model => model.ID)

    Please set these two link below @using(Html.BeginForm("Edit","Admin")).

    Second thing you can check while you click on somewhere to open edit page, that click event must be save the to keep that id like . new{model.id}.

    Make sure this will help for your requirement.

    Thanks.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 28, 2019 7:48 AM

All replies

  • User-1038772411 posted

    Hello,whiskets

    @Html.AntiForgeryToken()
    @Html.HiddenFor(model => model.ID)

    Please set these two link below @using(Html.BeginForm("Edit","Admin")).

    Second thing you can check while you click on somewhere to open edit page, that click event must be save the to keep that id like . new{model.id}.

    Make sure this will help for your requirement.

    Thanks.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, August 28, 2019 7:48 AM
  • User-898349087 posted

    thanks its good

    but why @using(Html.BeginForm()) do not need this two lines code?  

    @Html.AntiForgeryToken()
    @Html.HiddenFor(model => model.ID)
    Wednesday, August 28, 2019 8:23 AM
  • User-1038772411 posted

    Hello, whiskets

    you most welcome, and yes it seems no different between pass controller name, action name or not passed. if you haven't pass anything it returns null,null paramter in this case add and edit both method will work, diffrence only in edit time is hiddenfor() and antiforgottenkey().

    Thanks.

    Wednesday, August 28, 2019 10:14 AM
  • User-898349087 posted

    Thank for your help :)

    Wednesday, August 28, 2019 11:34 AM