why we used ajax. BeginForm in mvc instead adding form tags and Html.BeginForm - ajax

What is the use of Ajax.BeginForm in MVC4. Why do we use it, when we can just add a form tag directly, does this html helper add some capability or does something which cannot be done with a simple form tag. And also I have found something we can use Html.BeginForm for same purpose, So what is differences between them

""BeginForm()" is an extension method that writes an opening "" tag to the response. "BeginForm()" is an extension method for both HtmlHelper and AjaxHelper classes. It returns an MVCForm object from both HtmlHelper and AjaxHelper class instances so there is not much difference but the AjaxHelper method submits the form asynchronously using JavaScript."
You can also refer to the article for more details:
http://www.c-sharpcorner.com/UploadFile/3d39b4/working-with-html-beginform-and-ajax-beginform-in-mvc-3/

(1)Html.BeginForm will always use RouteTable to detrmine the action attribute value.
(2) provide client side validation
[http://weblogs.asp.net/imranbaloch/asp-net-mvc-client-side-validation-with-dynamic-contents]

Related

Can a view component call its own methods via ajax after rendering within the parent page?

Maybe I am missing the point, but if you have a ViewComponent, the examples ive seen so far, all do their work within their 'InvokeAsync method, where they are passed a model and return a view.
If the view contains a databound control and you need to bind to data via Ajax, where can those methods be, within the ViewComponent or the parent page?
Ok, so take this example
https://github.com/pkellner/progress-telerik-blog-viewcomponent/tree/master/WebApp/Pages/Components/RatingControl
Can the viewcomponent be used for helper methods that are called from its own view, eg with Ajax loading. Same question goes for other controls as well, eg a DataGrid within a viewcomponent, where would the variosu crud helper methods go?
Well, it finally dawned on me that NO you can not do what was suggesting. Per the docs, a ViewComponent (as least as of 3.0) do not respond directly as an http endpoint.
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-3.0
Solution - make an http endpoint, eg. a web api, which could be called via jquery/ajax from the markup in the viewcomponent.

Why unobtrusive validation wont work in asp.net mvc3 without using #Html.BeginForm()

To make unobtrusive validation work in asp.net mvc3 you have to use the html helper #Html.BeginForm() as mentioned in this very good post : http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html.
Without using the helper unobtrusive validation will not be triggered. I could verify that.
Can you explain me what does the helper #Html.BeginForm() do to allow unobtrusive validation to be triggered when the form is submitted ?
Can you also explain me how could I do that manually (read allow unobtrusive validation without calling the #Html.BeginForm()) ?
Please note that I know I can call unobtrusive validation using $("#myform").valid() but I would like to know the magic behind the helper and how to reproduce it.
When you call BeginForm (see http://j.mp/WrmAyk for the FormExtensionsclass), a new MvcForm object is created.
If you look in the constructor of this class (see http://j.mp/Wrml6F for the MvcForm class) you will see that it creates a new FormContext object: _viewContext.FormContext = new FormContext();.
When an input, textarea or select is rendered using the HTML helper, the following is called: tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata));, which takes care of rendering the validation attributes from the model metadata.
This GetUnobtrusiveValidationAttributes method (see http://j.mp/Wrn4oa for the HtmlHelper class) checks to see if the FormContext is null before rendering attributes:
FormContext formContext = ViewContext.GetFormContextForClientValidation();
if (formContext == null)
{
return results;
}
This is why no validation attributes are rendered unless you are within a form. You can get round this by creating a 'fake' FormContext, like #karaxuna suggests.
Write this in your view and it will work:
ViewContext.FormContext = ViewContext.FormContext ?? new FormContext();
When code is inside #Html.Beginform (in the same view), then html element validation attributes are got from metadata, In other case, it is not.

Request page content through System.Net WebClient in asp.net MVC

Umbraco ver. 4.7
My project is running along side asp.net MVC 4. I have a Umbraco page, which has a Rich Text editor property on the document type, that will retain a body of text with HTML.
Is there a way to use a System.Net.WebClient client, and request the Umbraco page from within my MVC project and have it return the content of that page's document property to the MVC controller's WebClient request?
Bonus Question:
Is there a way to setup an Umbraco macro in the template that will parse the querystring params and have place holders in the Umbraco template that the macro will replace the placeholders with the parsed out querystring params before the content is returned to the request (explained up above)?
Have you used the /Base extension in Umbraco? I believe this may help you out, because I had similar requirements and found /Base extremely powerful. In my document type I actually used a multi-line textbox as input for the html (or in my case Razor script). In my /Base class I created a method that finds the correct node, takes the raw script from the textbox, renders the script into a raw html string, and returns the string wrapped in a tag .
public static string GetRazor()
{
var doc = new DynamicNode(nodeId);
string razorScript = doc.GetPropertyValue("{propertyAlias}");
string razorString = RenderRazor.RenderRazorScriptString(razorScript, nodeId);
return razorString;
}
Another way is to create a macro within Umbraco which your template can call, something like:
#using umbraco.MacroEngines
#{
dynamic node = #Model;
string htmlString = node.GetPropertyValue("{propertyAlias}");
#Html.Raw(htmlString)
}
Then inside your template, you just need to inject the macro:
<umbraco:Macro Alias="{RazorAlias}" runat="server"></umbraco:Macro>
Whatever html in your textbox will be rendered by the razor engine!
-Dan
Add a reference to umbraco.dll and umbraco.MacroEngines.dll in your MVC4 project.
You should then be able to do (within your controller or view):
dynamic d = new DynamicNode(nodeId);
return d.AliasOfRichTextProperty

why i have to call or declare the jquery.validate.unobtrusive.min.js in each partial page in mvc

why i have to call or declare this jquery.validate.unobtrusive.min.js in each partial page where i need validations.
I have already define the js in master layout.
Thank You for your help
why i have to call or declare this jquery.validate.unobtrusive.min.js
in each partial page where i need validations.
No, you don't need to do that. Adding it once in the Layout is more than enough.
Of course if you add some partial HTML to your DOM using for example an AJAX call and this HTML contains form elements that need to be bound to unobtrusive validation you need to force their parsing using the following the parse method that you need to invoke immediately after adding or replacing some elements to the DOM:
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");

create custom controls mvc3

Just starting to get the hang of MVC3 and want to start building out some custom controls that I can just drop into a view. Specifically I want to be able to drop in some html form controls that will automatically add some javascript for validation.
something like this is what I'd want:
#Html.VTextBox("MyTextBox","",new {#vType="PhoneNumber", #vMessage="You Must Enter a Phone Number" })
when the page is rendered, I'd want it to search for any custom elements I create then drop in the appropriate javascript to validate client side. I did something very similar to this with asp.net web forms for custom controls ie
<ucc:VTextBox ID="MyTextBox" runat="server" message="You must fill this in" />
just wondering if MVC3 offers the same extensibility. Any resources or advice you can provide would be greatly appreciated.
TIA
To start off with, you'll need to look into extension methods and more specifically, how to create extension methods for the HtmlHelper class so you could write code like the example you've shown above.
For the example you've shown above, you could write code like this:
public MvcHtmlString VTextBox(string name, object value, object htmlAttributes)
{
StringBuilder html = new StringBuilder();
// Build your html however you want
// Here's a simple example that doesn't
// take into account your validation needs
html.AppendFormat("input type=\"text\" name=\"{0}\" value=\"{1}\" />", name, value);
return MvcHtmlString(html.ToString());
}
Then in your view you can use the example above like so:
#Html.VTextBox("MyTextBox","",new {#vType="PhoneNumber", #vMessage="You Must Enter a Phone Number" })
NOTE: You'll need to import the namespace the extension method is in to your view. Simplest method, put a #using ExtensionMethodNamespace at the top of your view. You can make the namespace automatically imported to all your views by fiddling with the web.config (and maybe the Global.asax).
ADDENDUM: Please note RPM1984's comment below where he advises to use TagBuilder in place of StringBuilder which is sound advice since this is the exact scenario TagBuilder was designed for. He also mentions strong typing the helper to the model which is also great advice.

Resources