How to pass a textbox value from view to a controller in MVC 4?

后端 未结 5 1414
我在风中等你
我在风中等你 2021-02-13 23:56

Here i am fetching the value from database and showing it in a input field


and

5条回答
  •  鱼传尺愫
    2021-02-14 00:33

    When you want to pass new information to your application, you need to use POST form. In Razor you can use the following

    View Code:

    @* By default BeginForm use FormMethod.Post *@
    @using(Html.BeginForm("Update")){
         @Html.Hidden("id", Model.Id)
         @Html.Hidden("productid", Model.ProductId)
         @Html.TextBox("qty", Model.Quantity)
         @Html.TextBox("unitrate", Model.UnitRate)
         
    }
    

    Controller's actions

    [HttpGet]
    public ActionResult Update(){
         //[...] retrive your record object
         return View(objRecord);
    }
    
    [HttpPost]
    public ActionResult Update(string id, string productid, int qty, decimal unitrate)
    {
          if (ModelState.IsValid){
               int _records = UpdatePrice(id,productid,qty,unitrate);
               if (_records > 0){                    {
                  return RedirectToAction("Index1", "Shopping");
               }else{                   
                    ModelState.AddModelError("","Can Not Update");
               }
          }
          return View("Index1");
     }
    

    Note that alternatively, if you want to use @Html.TextBoxFor(model => model.Quantity) you can either have an input with the name (respectecting case) "Quantity" or you can change your POST Update() to receive an object parameter, that would be the same type as your strictly typed view. Here's an example:

    Model

    public class Record {
        public string Id { get; set; }
        public string ProductId { get; set; }
        public string Quantity { get; set; }
        public decimal UnitRate { get; set; }
    }
    

    View

    @using(Html.BeginForm("Update")){
         @Html.HiddenFor(model => model.Id)
         @Html.HiddenFor(model => model.ProductId)
         @Html.TextBoxFor(model=> model.Quantity)
         @Html.TextBoxFor(model => model.UnitRate)
         
    }
    

    Post Action

    [HttpPost]
    public ActionResult Update(Record rec){ //Alternatively you can also use FormCollection object as well 
       if(TryValidateModel(rec)){
            //update code
       }
       return View("Index1");
    }
    

提交回复
热议问题