چندین Submit در یک Html Form و انتساب Action های مجزا به هر یک از Submit ها در MVC
نویسنده: مهران موسوی
تاریخ: ۱۳۹۱/۰۹/۲۲ ۱:۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
@model Models.MyModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>ViewPage1</title>
</head>
<body>
<div>
@using (Html.BeginForm("SendMessage", "Home", FormMethod.Post))
{
@Html.LabelFor(x => x.Name);
@Html.TextBoxFor(x => x.Name);
<input type="submit" value="ارسال توسط پیامک" name="Send_sms" />
<input type="submit" value="ارسال توسط ایمیل" name="Send_email" />
}
</div>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
namespace Models
{
public class MyModel
{
[DisplayName("نام خود را وارد کنید :")]
public string Name { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Reflection;
namespace ActionHandlers
{
public class SendMessageHandlerAttribute : ActionNameSelectorAttribute
{
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
return true;
if (!actionName.Equals("SendMessage", StringComparison.InvariantCultureIgnoreCase))
return false;
var request = controllerContext.RequestContext.HttpContext.Request;
return request[methodInfo.Name] != null;
}
}
}
[SendMessageHandler ]
[HttpPost]
public ContentResult Send_sms(MyModel mdl)
{
/// Do something ...
return string.Empty ;
}
[SendMessageHandler ]
[HttpPost]
public ContentResult Send_email(MyModel mdl)
{
/// Do something ...
return string.Empty;
}
[HttpPost]
public ActionResult MyAction([other params here], string buttonName1, string buttonName2, etc)
{
if(!string.IsNullOrEmtpy(buttonName1)) { //button1 was clicked}
}
<input type="submit" value="Standard action">
<input data-form-action="@Url.Action("mysecondaction")" type="submit" value="Second action">
$(document).on('click', '[type="submit"][data-form-action]', function(event) {
var $this = $(this),
formAction = $this.attr('data-form-action'),
$form = $($this.closest('form'));
$form.attr('action', formAction);
});