ورود

View Full Version : آموزش: چگونه از چندین دکمه post در یک Form در فریمورک asp.net mvc استفاده کنیم ؟



میلاد رئیسی
جمعه 28 آبان 1395, 08:03 صبح
در این آموزش میخوام بهتون یاد بدم که چطوری در یک فرم از چندین دکمه post استفاده کنید و هر کدوم به Action خاص خودشون اشاره کنن .
برای این کار راه های مختلفی وجود داره که من بهترین اون ها (از نظر شخص بنده ) رو انتخاب کردم و براتون به اشتراک میذرم :

میخواییم یک Attribut (https://blogs.msdn.microsoft.com/aspnetue/2010/02/24/attributes-and-asp-net-mvc/) بسازیم که وقتی اطلاعاتی که در Form هستش به وسیله دکمه Submit ارسال میشه به Action تشخیص بده که الان کدوم اکشن باید کار کنه :




[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultipleButtonAttribute : 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.GetValu e(keyValue);

if (value != null)
{
controllerContext.Controller.ControllerContext.Rou teData.Values[Name] = Argument;
isValidName = true;
}

return isValidName;
}
}


حالا نحوه ساختن دکمه های submit رو در View ببینید :


<form action="" method="post">
<input type="submit" value="Save" name="action:Save" />
<input type="submit" value="Cancel" name="action:Cancel" />
</form>


اینجا رو توجه کنید که چطور از Attribut ساخته شده استفاده میکنیم :


[HttpPost]
[MultipleButton(Name = "action", Argument = "Save")]
public ActionResult Save(MessageModel mm) { ... }

[HttpPost]
[MultipleButton(Name = "action", Argument = "Cancel")]
public ActionResult Cancel(MessageModel mm) { ... }


به همین راحتی !

امیدوارم تونسته باشم کمکی به عزیزان برنامه نویس کرده باشم .