How to unencode attribute when calling Html.BeginForm - asp.net-mvc

I'm trying to hook into Google Analytics and have this:
#using (Html.BeginForm("Register", "Account", FormMethod.Post,
new { id = "account-register-form",
onsubmit = "_gaq.push(['_link', 'someurl'])" }))
My rendered view then looks like this:
<form action="/Account/Register/Basic" id="account-register-form" method="post"
onsubmit="_gaq.push(['_link', 'someurl'])">
I have tried Html.Raw("_gaq.push(['_link', 'someurl'])") but this does not work, because I think BeginForm does the encoding.

Code works fine if don't turn off encoding but you can turn off attribute encoding by creating a class like this:
public class HtmlAttributeEncodingNot : System.Web.Util.HttpEncoder
{
protected override void HtmlAttributeEncode(string value, System.IO.TextWriter output)
{
output.Write(value);
}
}
and adding this to web.config under :
<httpRuntime encoderType="HtmlAttributeEncodingNot"/>

You don't need to unencode anything. What you have is perfectly valid markup and working javascript, as seen in the following live demo:
<form action="#" method="get" onsubmit="alert('some test');">
<input type="submit" value="OK" />
</form>
So keep your code as is.

If you don't have to use the Html.BeginForm then use can use the code snippet below to solve your formatting issue.
<form action="#Url.Action("Register", "Account")"
method="POST" id="account-register-form"
onsubmit="_gaq.push(['_link', 'someurl'])">
</form>
This outputs the html you require.

Related

Why must I use TextBoxFor to post values back to my controller?

I'm trying to post a model back to my controller. I'm not sure why TextBoxFor works and TextBox does not.
#ModelType Models.myModel
#Code
ViewData("Title") = "Foo"
End Code
#Using (Html.BeginForm())
#Html.AntiForgeryToken()
#Html.TextBoxFor(Function(m) m.Value) <--- works
#Html.TextBox(Model.Value) <--- does not work
#Html.TextBox("Value", Model.Value) <--- works! (per answer below)
#<input type="submit" value="Save" />
End Using
Html.TextBoxFor creates right input type="text" with correct name value. You mustn't use it, but it helps in this case. Same result may be achieved even with html code:
<input type="text" name="Value" value="#Model.Value" />
Main point for asp.net mvc model binders is correct names for html controls. Html.TextBox() also does it, using first parameter as html element name, so correct usage of it should be Html.TextBox("Value", Model.Value)

Calling controller from view, passing input text fields

I have two text inputs, content of which needs to be passed to a certain action as parameters when a button is clicked. I'm using MVC3
View:
<input name="input2" type="text" class="inputfield" id="datepicker_1" /></td>
<input name="input2" type="text" class="inputfield" id="datepicker_2" /></td>
#Html.Action("Search", ...)
Controller:
public ActionResult Search(...)
I suppose the object routeValues or RouteValueDictionary should be used in the #Html.Action for this. These object are confusing for me a bit. Could anyone clarify this for me please. Thank you!
The Html.Action will probably generate the link html before you provide the inputs. You need to either place your inputs inside a form to be submited to your action, or use ajax, with jquery perhaps, to call the action, like so:
#using (Html.BeginForm("Search", "Controller", FormMethod.Post, new { id = "frmAction" }))
{
<input name="datepicker_1" type="text" class="inputfield" id="datepicker_1" /></td>
<input name="datepicker_2" type="text" class="inputfield" id="datepicker_2" /></td>
}
[HttpPost]
public ActionResult Search(Datetime datepicker_1, Datetime datepicker_2) {...}
For an Ajax example, check this question:
jquery ajax forms for ASP.NET MVC 3
Hope this helps...
It seems like you need have a submit on your view, and then implement a post action on your controller, to handle the submit. I.e. something along the lines of
<input type="submit" value="Search..." />
in the view, and
[HttpPost]
public ActionResult Search(FormCollection collection)
the parameters depend on whether your view is strongly typed. The above assumes its not.

MVC File upload validation

I have a simple situation where I have a page that uploads Files, for some importing. At the moment, all I have is a file upload input on my page.
this is what my get controller looks like
public ActionResult FileUpload()
{
return View();
}
This is what my view looks like
#{
ViewBag.Title = "FileUpload";
}
<h2>FileUpload</h2>
<form action="/Home/FileUpload" method="post" enctype="multipart/form-data">
<input type="file" id="newFile" name="newFile" />
<input type="submit" id="submitButton" value="Submit" />
</form>
and this is what my post action looks like
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase newFile)
{
if (newFile.ContentLength > 0)
{
//do stuff here
}
return View("Index");
}
You will of course notice there is no mention of a model here as I cannot find a way to create a model for this situation. I would like to have some very basic validation, along the lines of 'please choose a file before you upload', thats all.
Is there a way to achieve this?!
Thanks in advance
Will
Create model class with string property newFile and put a Required on it.
In controller accept not HttpPostedFile but your model class.
You should add the client side validation manually:
<input type="file" data-val="true" data-val-required="please select a file" name="file" />
#Html.ValidationMessage("file")

Handling 2 buttons submit Actions in a single View/Form - ASP.NET MVC 2 RTM

I have a View in which the user is able to upload a file to the server.
In this view I also have 2 buttons: one to Upload a file and other to Download the last file imported.
In my Controller I created 2 action methods: Import and Export.
How could I manage to redirect each button click to the proper action method in my Controller?
I have tried Html.ActionLink:
<%= Html.ActionLink("Upload", "Import", "OracleFile")%>
<%= Html.ActionLink("Download", "Export", "OracleFile")%>
Html.ActionLink didn't do the trick. The action links were taking me to the right Action methods but they were generating a GET request. This way Request.Files.Count = 0.
I need a POST request.
Note: the most intriguing part is that the upload was working and all of sudden it stopped working. I've seen that some people are having the same problem with FileUpload tasks in which the Request.Files is always Empty. I think it's empty because you need a post to the server. Isn't it?
maybe this will give u the idea:
view:
<form enctype="multipart/form-data" method="post" action="/Media/Upload/Photo">
<input type="file" name="file" id="file" />
<input type="submit" name= "submitImport" value="Upload" />
<input type="submit" name = "submitExport" value="Download" />
</form>
controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Action (FormCollection formCollection)
{
if (formCollection["submitImport"] != null)
{
return Import(formCollection);
}
if (formCollection["submitExport"] != null)
{
return Export(formCollection);
}
}
the Export and Import are the appropriateactions
You have to use a "multipart/form-data" form, and submit the form. No ActionLink.
<form enctype="multipart/form-data" method="post" action="/Media/Upload/Photo">
<input type="file" name="file" id="file" />
<input type="submit" value="Upload" />
</form>
To generate a POST request for the upload, use the File Input form element and just post back to the server ala normal.
http://www.w3schools.com/jsref/dom_obj_fileupload.asp
Have a look at this blog post from Scott Hanselman.
http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx

Use the routing engine for form submissions in ASP.NET MVC Preview 4

I'm using ASP.NET MVC Preview 4 and would like to know how to use the routing engine for form submissions.
For example, I have a route like this:
routes.MapRoute(
"TestController-TestAction",
"TestController.mvc/TestAction/{paramName}",
new { controller = "TestController", action = "TestAction", id = "TestTopic" }
);
And a form declaration that looks like this:
<% using (Html.Form("TestController", "TestAction", FormMethod.Get))
{ %>
<input type="text" name="paramName" />
<input type="submit" />
<% } %>
which renders to:
<form method="get" action="/TestController.mvc/TestAction">
<input type="text" name="paramName" />
<input type="submit" />
</form>
The resulting URL of a form submission is:
localhost/TestController.mvc/TestAction?paramName=value
Is there any way to have this form submission route to the desired URL of:
localhost/TestController.mvc/TestAction/value
The only solutions I can think of are to create a separate action that just checks the request parameters, or to use Javascript.
Solution:
public ActionResult TestAction(string paramName)
{
if (!String.IsNullOrEmpty(Request["paramName"]))
{
return RedirectToAction("TestAction", new { paramName = Request["paramName"]});
}
/* ... */
}
In your route, get rid of the {paramName} part of the URL. It should be:
TestController.mvc/TestAction
As that is the URL you want the request to route to. Your form will then post to that URL.
Posted form values are mapped to parameters of an action method automatically, so don't worry about not having that data passed to your action method.
My understanding is that this is how HTML works. If you do a <form url="foo" method="get"> and post the form, then the form will post foo?
param1=value1&...&paramn=valuen
It has nothing to do with MVC.
Besides, what part of REST does that URL violate? It's not a pretty URL, but by strict definition of REST, it can be RESTful. REST doesn't specify that query parameters have to be in an URL segment. And in this case, those are query parameters.

Resources