Truyền và lấy dữ liệu từ View sang Controller trong MVC asp.net

Thảo luận trong 'Lập Trình Website MVC5 & MVC6' bắt đầu bởi admin, 26/9/17.

  1. admin
    Tham gia ngày:
    22/5/13
    Bài viết:
    4,878
    Đã được thích:
    1,193
    Điểm thành tích:
    113
    Giới tính:
    Nam
    Truyền và lấy dữ liệu từ View chuyển sang Controller trong mô hình MVC của web asp.net gồm rất nhiều cách khác nhau.
    Hôm nay mình sẽ hướng dẫn các bạn 4 cách truyền dữ liệu được sự dụng 99% tại MVC và 7 cách lấy dữ liệu tại Controller mà bạn nào học mô hình này cũng phải biết, sử dụng nó trong hết quảng đời làm web theo mô hình MVC này.

    4 cách truyền bao gồm : Request, Form Collection, Action Arguments, Model bạn có thể dụng bất kỳ cách nào cũng được, tùy vào dữ liệu nhiều ít và quen thì sử dụng, thường dùng 3 cách Request, Action Arguments, Model

    truyen-va-lay-du-lieu-tu-view-sang-controller-model.jpg

    1. Cách Request dữ liệu


    1.1 Cách truyền trên url web dạng tham số.


    Ví dụ ta có đường dẫn:
    Mã:
    http://localhost:58408/TruyenThamSoAction/ViDu1?ho=Phạm&ten=Sơn&congViec=IT
    Cách lấy: có 3 cách

    String value=Request["ParameterName"];
    String value=Request.QueryString["ParameterName"];
    String value=Request.Params["ParameterName"];

    VD:

    String value=Request["ho"]; // ho=Phạm
    String value=Request.Params["ten"]; // ten=Sơn
    String value=Request.Params["congviec"]; // congviec=ID

    Lưu ý: 3 cách trên đều giống nhau, bạn chọn cách nào cũng được

    1.2 Cách truyền theo url dạng ID.


    Xem cơ chế tại: App_Start - > RouteConfig.cs

    Theo cơ chế : {controller}/{action}/{id}

    VD 1: dưới dạng URL Get
    Mã:
    http://localhost:58408/ControllerViDu/ActionViDu/CongSon
    Cách lấy:
    Mã:
    Public ActionResult ActionViDu(string id)
    {
       //cái ta nhận được id = CongSon
    }
    
    Lưu ý: bắt buộc lúc lấy phải giống trên là biến id kiểu dữ liệu string nhé.

    VD 2: dưới dạng post truyền vào url dưới dạng button submit
    HTML:
    @using (Html.BeginForm("ActionViDu", "ControllerViDu", new { Id = 123, Name = "itseovn" }, FormMethod.Post))
    {
        <input type="submit" value="Lưu" />
    }
    Cách lấy:
    Mã:
    [HttpPost]
    public ActionResult ActionViDu(int Id, string Name)
    {
    //giá trị nhận được Id = 123, và Name = "itseovn"
    }
    

    1.3 Truyền và lấy dạng tham số kết hợp id.


    VD:
    Mã:
    http://localhost:58408/ControllerViDu/ActionViDu/Pham?ten=Sơn&congViec=IT
    
    Cách lấy:
    Mã:
    public ActionResult ActionViDu (string id)
    {
       ViewBag.Surname = id; // id=Pham
       ViewBag.Name = Request["ten"]; // ten=Sơn
       ViewBag.Job = Request["congViec"]; // congviec=IT
       return View();
    }
    

    2. Get&Post trong Controller với Form Collection


    VD: ta có form dữ liệu tại view như sau
    Mã:
    <form action="/Student/Register" method="post">
        Id <input name="Id" />
        Id <input name="Name" />
        Id <input name="Marks" />
        <input type="submit" value="Register" />
    </form>
    
    Có 2 cách lấy:

    2.1 Cách dùng Request.Form


    Cấu trúc: String Value=Request.Form["<tham số>"];

    VD:
    Mã:
    Public ActionResult Register()
    {
        String Id= Request.Form["Id"];
        String Name= Request.Form["Name"];
        double Marks= Convert.ToDouble(Request.Form["Marks"]);
        Return View();
    }
    

    2.1 Các dùng FormCollection


    VD:
    Mã:
    Public ActionResult Register(FormCollection Fields)
    {
       String Id= Fields["Id"];
       String Name= Fields["Name"];
       double Marks= Convert.ToDouble(Fields["Marks"]);
       Return View();
    }
    

    3. Sử dụng Action Arguments


    truyen-du-lieu-dang-action-arguments.png

    4. Sử dụng Model


    VD: ta có Form
    Mã:
    <form action="/Student/Register" method="post">
        Id <input name="Id" />
        Id <input name="Name" />
        Id <input name="Marks" />
        <input type="submit" value="Register" />
    </form>
    Cách lấy dữ liệu bằng Model:

    B1: tạo 1 Class trong Models để lấy dữ liệu truyền từ Form Action truyền đi, Click chuột phải vào folder Models chọn tạo mới 1 class.
    Mã:
    Public string StudentInfo
    {
       Public string Id {get; set;}
       Public string Name {get; set;}
       Public double Marks {get; set;}
    }
    B2: tạo 1 ActionResult trong controller để lấy dữ liệu ra
    Mã:
    Public ActionResult UserModel(StudentInfo model)
    {
       String Id= model.Id;
       String Name= model.Name;
       double Marks= Convert.ToDouble(model.Marks);
       Return View();
    }

    5. Truyền dữ liệu từ File sang Controller


    Để Upload file hình ảnh từ View sang Controller để upload hình xuống hosting website các bạn làm theo ví dụ và hướng dẫn cách upload file hình trong code c# MVC sau nhé.

    VD: ta có View dữ liệu như sau:
    Mã:
    @using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
    //vì form này có thuộc tính upload file lên, nên phải khai báo ..."multipart/form=-data" đầy đủ
    {
             <input type="file" name="upPhoto" />
            <button class="btn btn-default">
                <span class="glyphicon glyphicon-upload"></span> UpLoadFile
            </button>
    }

    Cách 1: truyền từ View sang controller sử dụng HttpPostedFileBase


    Mã:
    [HttpPost]
    public ActionResult ActionName(HttpPostedFileBase file)
    {
       var ext = Path.GetExtension(file.FileName).ToLower(); //lấy đuôi của file
       var FileName = Path.GetFileName(file.FileName); // lấy tên file
       var FileNameNull = FileName.Remove(FileName.LastIndexOf(".")); //lấy mỗi tên file không chưa đuôi file.
       if (ext == "" || (ext != ".jpg" && ext != ".png" && ext != ".jpeg" && ext != ".gif"))
       {
           ModelState.AddModelError("","File phải có đuôi jpg, png, gif");
       }
       else if (file.ContentLength > 0 && file.ContentLength < 2048576 && FileName != "")
       {
           var path = Path.Combine(Server.MapPath("~/images"), FileName);
           file.SaveAs(path);
           ModelState.AddModelError("","Lưu file thành công");
       }
       else
       {
           ModelState.AddModelError("","File không tồn tại hoặc file phải nhỏ hơn 2MB");
       }
       return View();
    }
    

    Cách 2: Lấy thông qua Request.Files


    Mã:
    [HttpPost]
    public ActionResult ActionName()
    {
       var file = Request.Files["upPhoto"];
       var ext = Path.GetExtension(file.FileName).ToLower(); //lấy đuôi của file
       var FileName = Path.GetFileName(file.FileName); // lấy tên file
       var FileNameNull = FileName.Remove(FileName.LastIndexOf(".")); //lấy mỗi tên file không chưa đuôi file.
       if (ext == "" || (ext != ".jpg" && ext != ".png" && ext != ".jpeg" && ext != ".gif"))
       {
           ModelState.AddModelError("","File phải có đuôi jpg, png, gif");
       }
       else if (file.ContentLength > 0 && file.ContentLength < 2048576 && FileName != "")
       {
           var path = Path.Combine(Server.MapPath("~/images"), FileName);
           file.SaveAs(path);
           ModelState.AddModelError("","Lưu file thành công");
       }
       else
       {
           ModelState.AddModelError("","File không tồn tại hoặc file phải nhỏ hơn 2MB");
       }
       return View();
    }
    

    6. Lấy Parameter value tại View


    Nếu sử dụng Router Param
    Mã:
    @(ViewContext.RouteData.Values["parameterName"])
    VD: controller/update/12/
    @(ViewContext.RouteData.Values["Id"])
    Giá trị trả về là id bằng: 12

    Không sử dụng Router Param
    Mã:
    Request.Params["paramName"]
    • VD: controller/update/?Id=13
    • Request.Params["Id"]
    • Giá trị trả về là id bằng: 13

    7. Truyền thông qua Ajax


    7.1 Truyền dạng FromData (Request.Form)


    Trong View:
    HTML:
    $(".btnButton").click(function () {
        var item1 = $("#dropdownlist option:selected").val();
        var item2 = $("[name='Nametitle']").val();
        var item3 = false;
        if ($('#checkedbox').is(":checked")) {
            item3 = true;
        }
        var formdata = new FormData();
        formdata.append("ddlist", item1);
        formdata.append("title", item2);
        formdata.append("checkbox", item3);
        $.ajax({
            url: '/controller/actionA',
            type: "POST",
            contentType: false, // Not to set any content header
            processData: false, // Not to process data
            data: formdata,
            async: false,
            success: function (result) {
               //success
               alert(result);
            },
            error: function (err) {
                alert(err.statusText);
            }
        });
    });
    Trong controller nhận dữ liệu:
    Mã:
    public ActionResult actionA()
    {
        var ddlistvalue = Request.Form["ddlist"];
        var titlevalue = Request.Form["title"];
        var checkboxvalue= Request.Form["checkbox"];
        ///xử lý.....
        return Json("xử lý thành công", JsonRequestBehavior.AllowGet);
    }
    

    7.2 Truyền dạng Request tham số


    Trong View
    HTML:
    $(".btnButton").click(function () {
        var item1 = $("#dropdownlist option:selected").val();
        var item2 = $("[name='Nametitle']").val();
        var item3 = false;
        if ($('#checkedbox').is(":checked")) {
            item3 = true;
        }
        $.ajax({
            url: '/controller/actionA',
            type: "POST",
            data: { ddlistvalue: item1, titlevalue: item2,checkboxvalue: item3 },
            success: function (response) {
                ////success
               alert(response);
            },
            error: function (err) {
                alert(err.statusText);
            }
        });
    });
    Trong controller nhận dữ liệu:
    Mã:
    public ActionResult actionA(string ddlistvalue, string titlevalue, string checkboxvalue)
    {
        ///xử lý.....
        return Json("xử lý thành công", JsonRequestBehavior.AllowGet);
    }
    
    VD: bạn muốn truyền của file Upload và 1 texbox nào đó bằng ajax vào controller thì làm như sau:

    Trong View
    HTML:
    <input id="titlepicture"  type="text" placeholder="Tiêu đề hình" value="">
    <input id="fileuploadpicture" onchange="pressed()" type="file" name="fileuploadpicture" multiple />
    <script>
    $(".btnButton").click(function () {
        var itemtitle = $("#titlepicture").val();
        var fileUpload = $("#fileuploadpicture").get(0);
        var files = fileUpload.files;
        var formdata = new FormData();
        for (var i = 0; i < files.length; i++) {
             formdata.append(files[i].name, files[i]);
        }
        formdata.append("title", itemtitle);
        $.ajax({
            url: '/controller/actionA',
            type: "POST",
            contentType: false, // Not to set any content header
            processData: false, // Not to process data
            data: formdata,
            async: false,
            success: function (result) {
               //success
               alert(result);
            },
            error: function (err) {
                alert(err.statusText);
            }
        });
    });
    </script>
    
    Trong controller nhận dữ liệu:
    Mã:
    public ActionResult actionA()
    {
        var titlevalue = Request.Form["title"];
        HttpFileCollectionBase files = Request.Files;
        if (files != null && files.Count > 0)
        {
           for (int i = 0; i < files.Count; i++)
           {
                  //load for lấy ra tất cả các file.
                  HttpPostedFileBase file = files[i];
                  var fname = Path.Combine(Server.MapPath("~/uploads/"), file.FileName);
                  file.SaveAs(fname);
           }
       }
       return Json("Lưu ảnh thành công", JsonRequestBehavior.AllowGet);
    }
    
     
    Cảm ơn đã xem bài:

    Truyền và lấy dữ liệu từ View sang Controller trong MVC asp.net

    Chỉnh sửa cuối: 21/9/23
  2. !kjsslv
    Tham gia ngày:
    20/12/18
    Bài viết:
    1
    Đã được thích:
    0
    Điểm thành tích:
    1
    Giới tính:
    Nam
    Bài viết rất hay nha :D
     
  3. Nocrobi
    Tham gia ngày:
    13/12/18
    Bài viết:
    22
    Đã được thích:
    0
    Điểm thành tích:
    1
    Giới tính:
    Nữ
    hách não quá ad ơi, thật khổ cho dần mù công nghệ
     
  4. NothingnessLs
    Tham gia ngày:
    24/12/18
    Bài viết:
    10
    Đã được thích:
    0
    Điểm thành tích:
    1
    Giới tính:
    Nam
    Mở lớp online đi bro ADmin hehe
     
  5. helennguyen2255
    Tham gia ngày:
    11/12/18
    Bài viết:
    19
    Đã được thích:
    0
    Điểm thành tích:
    1
    Giới tính:
    Nữ
    Admin chuyên nhiều món quá
     


Chủ để tương tự : Truyền lấy
Diễn đàn Tiêu đề Date
Lập Trình Website MVC5 & MVC6 Truyền và lấy dữ liệu từ Controller sang View trong MVC asp.net 26/9/17
Lập Trình Website MVC5 & MVC6 Truyền giá trị mặc định cho @Html.TextBox bằng ViewBag MVC 6/8/18
Lập Trình Website MVC5 & MVC6 Binding truyền dữ liệu vào DropDownList trong MVC Asp.net 23/7/18
Lập Trình Website MVC5 & MVC6 Lấy id mã máy tính duy nhất trọn bộ trong c# mvc asp.net 4/4/20
Lập Trình Website MVC5 & MVC6 Lấy Entity Value old cũ sau đó Update không bị lỗi Asp.net MVC 27/3/20