Chủ Nhật, 7 tháng 8, 2016

MVC4: Thiết lập nhiều sự kiện của button trên một Form

MVC4: Thiết lập nhiều sự kiện của button trên một Form
2015/04/21

Trong khi chúng ta phát triển một web app trên ASP.Net MVC, sẽ có trường hợp chúng ta sẽ có nhiều button trên 1 form. Mỗi button là 1 event riêng biệt sử dụng chung các properties của form. 
Tất nhiên chúng ta sẽ có rất nhiều cách để có thể thực hiện điều này. Chẳng hạn, tạo 1 hidden field [command], sau đó dùng javascript để set giá trị cho biến [command] rồi khi lên controller ta sẽ phân biệt từng command để thực hiện các logic thích hợp. Thế nhưng không cool :). 
Bài viết này sẽ hướng dẫn thiết lập để route đến đúng action cần thiết, tương tự như MVC bình thường.
Bước 1:
Thừa kế 1 ActionNameSelectorAttribute để routing tới action cần thiết.
namespace MultiEventsOnForm  
{
    public class MultiButtonAttribute : ActionNameSelectorAttribute
    {
        public string Name { get; set; }
        public string Argument { get; set; }
 
        public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
        {
            var isValidName = false;
            var keyValue = string.Format("{0}:{1}", Name, Argument);
            var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);
 
            if (value != null)
            {
                controllerContext.Controller.ControllerContext.RouteData.Values[Name] = Argument;
                isValidName = true;
            }
 
            return isValidName;
        }
    }
}
Bước 2:
Trên các action chúng ta sẽ khai báo thêm 1 annotation:
[HttpPost]
[MultiButton(Name = "action", Argument = "Hello")]
public ActionResult Hello()  
{
ViewBag.Message = "Hello";

return View("Index");  
}

[HttpPost]
[MultiButton(Name = "action", Argument = "Greeting")]
public ActionResult Greeting()  
{
ViewBag.Message = "Greeting";

return View("Index");  
}
Bước 3:
Tại view, chúng ta khai báo giá trị để route button đến action
<input type="submit" value="Hello" name="action:Hello"/>  
<input type="submit" value="Greeting" name="action:Greeting"/>  
Kết quả:
Index: 
Load
Sau khi ấn button Hello 
After click Hello
Sau khi ấn button Greeting 
After click Greeting
Source:

Không có nhận xét nào:

Đăng nhận xét