using two submit buttons inside single form

偶尔善良 提交于 2019-11-29 14:37:07

Show this page.

ASP.NET MVC – Multiple buttons in the same form - David Findley's Blog

Create ActionMethodSelectorAttribute inherit class.

Try this instead:

<input type="submit" value="Send" name="send" />
<input type="submit" value="Save As Draft" name="save" />

and:

public ActionResult SendEmail(string send, FormCollection form)
{
    if (!string.IsNullOrEmpty(send))
    {
        // the Send button has been clicked
    } 
    else
    {
        // the Save As Draft button has been clicked
    }
}

Hidden Html elements will be submitted with your form, so you could add a hidden element and modify it on button click before submission. Return true to continue with form submission.

@Html.Hidden("sendemail", true)
<input type="submit" value="Send"
       onclick="$('#sendemail').val(true); return true" />
<input type="submit" value="Save As Draft"
       onclick="$('#sendemail').val(false); return true;" />

Now you can just pull the value out of your form collection.

public ActionResult SendEmail(FormCollection form)
{
   if(Boolean.Parse(form["sendemail"]))
   {
      //Send Email
   }
   else
   {
      //Save as draft
   }
   return RedirectToAction("SendEmailSuccess");
}

Rather than using the FormCollection directly though, the best practice would be to create a view model that contains the specified property.

View Model

public class FooViewModel
{
  public bool SendEmail { get; set; }
  // other stuff
}

HTML

// MVC sets a hidden input element's id attribute to the property name, 
// so it's easily selectable with javascript
@Html.HiddenFor(m => m.SendEmail)

// a boolean HTML input can be modified by setting its value to
// 'true' or 'false'
<input type="submit" value="Send"
       onclick="$('#SendEmail').val(true); return true" />
<input type="submit" value="Save As Draft"
       onclick="$('#SendEmail').val(false); return true;" />

Controller Action

public ActionResult SendEmail(FooViewModel model)
{
   if(model.SendEmail)
   {
      //Send Email
   }
   else
   {
      //Save as draft
   }
   return RedirectToAction("SendEmailSuccess");
}

work around: use javascript for submiting the form instead of submit buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!