I have the following form
<form id="file_upload" action="/Upload/Save" method="POST" enctype="multipart/form-data">
<input type="text" id="txtProposalName" name="name" placeholder="Nome da Camiseta" />
<input type="text" id="txtProposalDesc" name="description" placeholder="Descrição da Camiseta"/>
<div class="fileupload-buttonbar">
<div class="progressbar fileupload-progressbar"></div>
<span class="fileinput-button">
Upload images
<input type="file" name="files[]" multiple />
</span>
</div>
<input type="hidden" id="imgID" name="imgID"/>
<input type="submit" id="postProposal"/>
Would call this action:
[HttpPost]
public JsonResult Save(string name, string description, string imgID)
{
return Json("a");
}
(This is the current implementation, it has no logic because I am still testing some things).
My problem is: when I click on my submit button, the action is called with the correct values, but when it returns, my browser redirects to /Upload/Save (which is the action URL).
Why is this happening? Is there any way to prevent it?
Thanks!
You can use an asynchronous call to your method (e.g. AJAX) to prevent the page from reloading.
You can use Ajax.BeginForm to prevent reload page.
As I can see you use full page reload with:
action="/Upload/Save"
Also you trying to post data to json action method in controller. You need all form submit make with jquery, most problems you will find with ajax file uploaders.
Added:
Also look at serialize() it will help you to collect all form input values.
Dont need to prevent it, just redirect the user in your server code .
Related
I have multiple buttons submitting a form. I check to see which button was clicked by the input value that gets passed into my controller.
public async Task<ActionResult> MyAction(MyModel model, string command)
The html below works. In my controller command equals myValue
<input type="submit" name="command" value="myValue" />
The html below doesn't work. In my controller command is null
<input type="image" name="command" src="..." value="myValue"/>
W3C says the type 'image' is a submit button
So why are these two input elements behaving differently?
An image submit button indeed behaves differently, by definition, both according to the expired working draft linked to in the question and the current HTML5 CR draft and the HTML 4.01 recommendation. According to HTML5 CR, construction of the form data set does not add a name=value pair for an image submit button but name.x=... and name.y=... with the coordinates of the clicked location as values. This corresponds to old definitions and browser practice, except that Chrome additionally adds a name=value pair.
Thus, in your case, the form data will contain the fields command.x and command.y, with values that you are probably not interested in. This is what you need to take as starting point when coding the form handler. This means that if you need to recognize which of several image buttons was used, you need to give them different name attributes.
You can have one hidden field and set the command name in that hidden field which ever button is click and get the name of the button that submited the form on server side.
Javascript
$(".submit").click(function(){
var commandName = $(this).attr("val");
$("input[type=hidden]").val(commandName);
});
HTML
<form>
<input type="hidden" name="command">
<input type="submit" value="submitbtn" class="submit" />
<input type="image" src="..." value="imagebtn" class="submit"/>
</form>
The simplest (and maybe not safe) way to accomplish this task is with inline JQuery, here's how :
VIEW :
<input type="image" src="..." onclick="$('#hidImgValue').val('Image1');" />
<input type="hidden" id="hidImgValue" name="command" value="none" />
CONTROLLER :
public async Task<ActionResult> MyAction(MyModel model, string command)
Command var will have "Image1" as value.
I have implemented an email sharing service in my web application. People can click on the email button and access a form with which they can send emails to whom they want.
I would like to set a default subject and body.
In the default body text of the email, I would like to pass the link of the page people want to share. Surely it is possible to do so but I do not manage to.
So far it has been a dead end to try to pass the link in the value argument of my text editor. I cannot think if any other way to do it.
Any suggestion greatly appreciated.
The same way you pass data to any other fields that you want to populate.
For example your controller returns a model emailShare that contains subject, body and url etc
In your gsp, lets say you have a textarea for the body of your email,
<g:textField name="emailSubject" value="${emailShare.subject}" />
<g:textArea name="emailBody" value="${emailShare.url}" rows="5" cols="40"/>
This will set the url as the default text in the textarea, which can also be further edited to add more text.
You can get the location of the current page using JavaScript with document.URL Then you can just set a hidden field on your form and submit it with your email request. For example:
<html>
<head>
<script type="text/javascript">
function setLocation(urlField) {
urlField.value = document.URL
}
</script>
</head>
<body>
<form id="exampleForm" name="exampleForm" action="#">
<input type="text" id="url" name="url"/>
<input name="submit" value="submit" type="button" onclick="setLocation(this.form.url);" />
</form>
</body>
</html>
I am using an id value that I pass in a hidden field. When the user submits the form I need the hidden field for my update. After the update, a new value is placed in the hidden field in the model and sent back to the view. What seems so strange is the helper always uses the first value, never updates. For example, look at the following from the View:
<%: Html.Hidden("MyId",Model.MyId) %>
<%: Model.MyId %>
First time in a look at the source in the browser yields:
<input type="hidden" id="MyId" name="MyId" value="1" />
1
** submit back to controller and model updates the MyId property to 2.
Back at the browser I now find:
<input type="hidden" id="MyId" name="MyId" value="1" />
2
The very same model property has different values! The helper method is somehow grabbing it from a prior model instance or something?
Any help greatly appreciated on what I am not understanding. BTW..get the same behavior with Html.TextBox and Html.TextBoxFor.
Thanks.
That's how HTML helpers work and it's by design. When binding they will first look at the value in the GET/POST request to see if the value is present and after that in the model. If a value is found in the request they will simply ignore the value you set in the model.
Normally you are not supposed to modify the data sent in the request inside your controller action. But if anyhow you decide to do it you will need to either roll your own helper or simply:
<input type="hidden" name="MyId" value="<%= Model.MyId %>" />
I'm trying to add a search box to a master page in an ASP.Net MVC web app. What's confusing me is how to properly implement it in the master page. So the user types in data into this search box, how should the data be handled from an MVC perspective?? I know I could use he master page's code behind, but I shouldn't. I'm currently trying to use a user control for this, but I'm not sure how to properly implement it and online resources seem to be limited. Would creating an HTML helper be best??
To summarize: Implement a search box in the MVC master page that directs to a different website and includes the user's query that they typed in the search box.
Is it better to use:
Master Page's codebehind
A user control
Or create a separate HTML Helper.
UPDATE:
Ok, per queen3's advice, I implemented a SearchController and used the HTML Helper BeginForm to generate a search box.
Controller action:
Function SearchWiki(ByVal q As String) As ActionResult
Return Redirect("http://home/search/Results.aspx?k=" & q & "&s=IT%20FAQ")
End Function
And in the Master Page:
<% Using Html.BeginForm("SearchWiki", "Search", FormMethod.Post)%>
<input type="text" name="q" />
<input type="submit" value="Search" />
<% End Using%>
But when I try to debug, the SearchWiki function never gets called and, as a result, nothing happens when I type in the search box and hit Search.
Forget about codebehind and user controls if you're going to use ASP.NET MVC. You need HTML, CSS, and JavaScript.
I suppose you want something like
<form action="<%= Url.Action("Index", "Search") %>" method="post">
<input type="text" name="q" />
</form>
With helpers it will be something like
<% Html.BeginForm("Index", "Search") %>
<input type="text" name="q" />
<% Html.EndForm() %>
Just put this into master page where appropriate in you site design. Then create SearchController to handle request, and return View() with search results. You may make form use GET instead of POST if you accept google-like search requests /Search?q=text.
The controller is very simple:
public class SearchController: Controller
{
public ActionResult Index(string q)
{
return View(SearchHelper.DoSearch(q));
// or return Redirect("http://site?q=" + q) if you want redirect
}
}
To summarize: Implement a search box
in the MVC master page that directs to
a different website and includes the
user's query that they typed in the
search box.
Seems like you want to use a different search provider. In this case you don't need any server-sided code at all... only pure html. I'll give you an example with Google:
<form id="search" action="http://www.google.com.br/search" method="GET">
<input type="text" name="q" />
<input type="submit" value="Submit" />
</form>
Just add this code on your MasterPage and we're done.
You can also add some JQuery to append the string "site:www.yoursite.com" to the search query. Doing so you can ask google to search the keywords on your site. The javascript code should be:
$("#search").submit(function(){
var input = $(this).find('input[name=q]');
var query = input.val() + ' site:www.yoursite.com';
input.val(query);
});
I have form area in my view. If I click button A, I want to submit to /Books/1 and if I click button B, I want to submit to /Books/2
How do I achieve this with MVC?
<form id="form1" name="form1" action="/Books/" method="get">
<input type="text" name="search" value="">
<input type="submit" name="id" value="1">
<input type="submit" name="id" value="2">
</form>
It sounds like what you want to do is call the Books Controller, with, say, the Search action. So for instance you might want to call /Books/Search/<search expression>/1, or /Books/Search/<search expression>/2, etc. (There's a few different ways you could be formatting these URLs, but it's mostly a matter of personal preference I think) If you want the URLs to appear as you've got them above (without the action in the URL), that can be accomplished with routing, something like this:
routes.MapRoute(
"Books",
"Books/{searchExpr}/{pageId}",
new { controller = "Books", action = "Search", searchExpr = "", pageId = 1 }
);
I think the main problem is that you're trying to use the WebForms PostBack everything paradigm in a situation where you're probably better off sending the information to the server in the URL or query string. The only time you're actually going to be posting form data here is when the user actually types something into the search box and clicks the Search button - at that point, the controller will pass the search expression to the appropriate View by stuffing it in ViewData, and from there, the View can pull it out and repopulate that textbox on the results page.
MVC Views can have multiple forms on a 'page', so just create separate sections and give each one their own form action.
<form id="form1" name="form1" action="/Books/1" method="get">
<!--...form fields-->
</form>
<form id="form2" name="form2" action="/Books/2" method="get">
<!--...form fields-->
</form>
I have never seen the ability to have a form field attached to two forms, seems like it wouldn't work. What you can do is put a hidden field in the second form which, on submission, grabs the information from the textbox in the first form.