We are using submit buttons (input type=submit) for submitting the form back to the server.
We have other buttons in the page as link button, so we had different look & feel between submit button and others.
We wanted create a submit button that looks like other link button as well as it should do the submit functionality by own.
So we decided to create a extension method.
To submit the page, i used the below code in the href.
document.forms['" + formId + "'].action = '" + href + "';
document.forms['" + formId + "'].method = 'POST';document.forms['" + formId + "'].submit();
To manually call the microsoft client side validation, i used the below code in the href.
Sys.Mvc.FormContext.getValidationForForm(document.forms['" + formId + "']).validate('submit').length
Find the extension method below
public static MvcHtmlString SubmitLinkButton(this HtmlHelper helper,
string caption,
string actionName,
string id,
string formId,
RouteValueDictionary routeValues = null,
Dictionary htmlAttributes = null)
{
return CreateLinkButton(helper, caption, actionName, id, routeValues, htmlAttributes, formId, null);
}
private static MvcHtmlString CreateLinkButton(HtmlHelper helper,
string caption,
string actionName,
string id,
RouteValueDictionary routeValues = null,
Dictionary htmlAttributes = null,
string formId = null,
string href = null)
{
string cssClass = "t-grid-action t-button t-state-default";
if (href != null)
{
href = "#";
}
else
{
formId = formId ?? "0";
//creating href string
href += "/" + helper.ViewContext.RouteData.Values["controller"].ToString();
href += "/" + actionName;
//QueryString can be found here - helper.ViewContext.Controller.ControllerContext.HttpContext.Request.QueryString
if (routeValues != null && routeValues.Count > 0)
{
href += "?";
href = routeValues.Aggregate(href, (current, routeValue) => current + (routeValue.Key + "=" + routeValue.Value + "&"));
href = href.Substring(0, href.Length - 1);
}
href = "javascript:{if (!Sys.Mvc.FormContext.getValidationForForm(document.forms['" + formId + "']).validate('submit').length) { document.forms['" + formId + "'].action = '" + href + "';document.forms['" + formId + "'].method = 'POST';document.forms['" + formId + "'].submit();}}";
}
var linkButtonBuilder = new TagBuilder("a");
linkButtonBuilder.GenerateId(id);
linkButtonBuilder.MergeAttributes(htmlAttributes);
linkButtonBuilder.AddCssClass(cssClass);
linkButtonBuilder.MergeAttribute("print_mode", "hide");
linkButtonBuilder.MergeAttribute("href", href);
linkButtonBuilder.SetInnerText(caption);
return MvcHtmlString.Create(linkButtonBuilder.ToString());
}