วันเสาร์ที่ 28 พฤศจิกายน พ.ศ. 2558

C# การสร้าง form register พร้อมการ upload รูปภาพ

1. สร้าง Model รับข้อมูล

    public class UserModel
    {
        public string FirstName { get; set; }

        public string LastName { get; set; }

        public HttpPostedFileBase File { get; set; }
    }

2.สร้าง function รับค่าใน controller

        public ActionResult Register(UserModel model)
        {
            if (model.File != null && model.File.ContentLength > 0)
            {
                var filename = Path.GetFileName(model.File.FileName);
                var path = Path.Combine(Server.MapPath("~/content/pics"), filename);
                model.File.SaveAs(path);
            }
            return RedirectToAction("Index");
        }

3. สร้าง form ใน view
    @using (Html.BeginForm("ชื่อฟังชัน", "ชื่อcontroller", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.LabelFor(m => m.FirstName)
        @Html.TextBoxFor(m => m.FirstName)
        @Html.LabelFor(m => m.LastName)
        @Html.TextBoxFor(m => m.LastName)
        <input type="file" name="file" />
        <input type="submit" value="Search" />
    }

ไม่มีความคิดเห็น:

แสดงความคิดเห็น