suppose i store url in database and now i want my form action attribute or ActionLink url should point to url stored in my database. when we use ActionLink then we specify controller & action method name and same way when we use @Html.BeginForm() then we also specify controller & action method name. so how can we customize the code for ActionLink & BeginForm() as a result it should always point to url which is stored in database. please guide me with concept. thanks
2 Answers
Why would you want to use the ActionLink or BeginForm helpers if you want to use an url stored in your database?
<a href="@Model.UrlComingFromYourDatabase">Click me</a>
seems just fine. Those helpers are designed to be used to compose an url by giving a controller and action names.
2 Comments
Mou
in case of BeginForm() how one can specify url ? suppose url is stored in variable and that variable need to use to set form action...how to do it with BeginForm() ? any guide line!
Darin Dimitrov
You could do it like this:
<form action="@Model.UrlComingFromYourDatabase" method="post">...</form>.To me just putting the html tags with the model is too verbose I would prefrer to create a custom html helper which will encapsulate the logic behind the tag rendering you can take a look to the mvc code here, but it could be something like this:
private static MvcForm MyFormHelper(this HtmlHelper htmlHelper, string formAction, FormMethod method, IDictionary<string, object> htmlAttributes)
{
//you can use service locator for getting your database artifacts
//place your custom logic
TagBuilder tagBuilder = new TagBuilder("form");
tagBuilder.MergeAttributes(htmlAttributes);
// action is implicitly generated, so htmlAttributes take precedence.
tagBuilder.MergeAttribute("action", formAction);
// method is an explicit parameter, so it takes precedence over the htmlAttributes.
tagBuilder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true);
bool traditionalJavascriptEnabled = htmlHelper.ViewContext.ClientValidationEnabled
&& !htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled;
if (traditionalJavascriptEnabled)
{
// forms must have an ID for client validation
tagBuilder.GenerateId(htmlHelper.ViewContext.FormIdGenerator());
}
htmlHelper.ViewContext.Writer.Write(tagBuilder.ToString(TagRenderMode.StartTag));
MvcForm theForm = new MvcForm(htmlHelper.ViewContext);
if (traditionalJavascriptEnabled)
{
htmlHelper.ViewContext.FormContext.FormId = tagBuilder.Attributes["id"];
}
return theForm;
}
1 Comment
liuhongbo
ViewContext.FormIdGenerator is a internal method you wont be able to just do that in your code.