<% using (Html.BeginForm("SearchByZip", "Dealer", new { zip = ""}, FormMethod.Get))
{ %>
<div>
<input type="text" class="padLeft" name="Zip" id="Zip" style="width: 200px" />
<input type="submit" class="btnFind" value="Find" />
</div>
<% } %>
This gives me the url "Dealer/SearchByZip?Zip=12345"
I would like to end up with this: "Dealer/Zip/12345"
(if I manually type in the url "Dealer/Zip/12345" it returns the right results, but when I click in submit it comes up with "Dealer/SearchByZip?Zip=12345"
What am I missing?
routes.MapRoute(
"DealerSearchByZip",
"Search/Zip/{zip}",
new { Controller = "Dealer", action = "SearchByZip", zip = "" }
);
This is happening because "Zip" is an input field in your form, not route data. So, when the page is rendered it creates a url using the default route ("DealerSearchByZip" route wasn't matched because Zip wasn't given as route data).
You could accomplish this via javascript, by updating the "action" attribute on the form when the "zip" field is updated.
Example using jQuery:
$('input[name=Zip]').update(function(){
$('form').attr('action', 'Dealer/Zip/' + $(this).val());
});
Or, since Zip is the only value you're worried about,
$('form').submit(function(){
window.location = 'Dealer/Zip/' + $('input[name=Zip]').val();
});
Related
In my View i have the following code:
<input type="text" id="createdDate" placeholder="dd/mm/yyyy" />
Download
In my Control i have de following code:
[HttpGet]
public async Task<IActionResult> GetRoomAccessHistory(DateTime createdDate)
{
// TO DO
}
In this particular case, i want to pass the createdDate value that is inside the textbox (createdDate) to my Url.Action(...), so it could be passed as a queryString in my URL.
This action is invoked as a GET request, and in GetRoomAccessHistory control method, i should get my createdDate.
Thank you.
PS
I think the solution should be something like this:
<a href="#Url.Action("GetRoomAccessHistory", "Files", new { createdDate = ??? })" >Download</a>
I have got a possible answer:
<form method="post" enctype="multipart/form-data" asp-action="GetRoomAccessHistory" id="formGetRoomAccessHistory">
...
<button type="button" id="downloadRoomAccessHistory"</button>
</form>
<script>
var form = document.getElementById("formGetRoomAccessHistory");
document.getElementById("downloadRoomAccessHistory").addEventListener("click", function () {
form.submit();
});
</script>
This does exactly what i want and it works, but i was trying to find a more nice solution because my experience in ASP.NET MVC is low.
You're using the wrong tool for the job.
Since the Url.Action() helper runs on the server-side, it has already executed when the page was first loaded, and generated a fixed URL which is inserted into the page's HTML. It cannot know what the user later enters into the textbox.
If you want to capture data which a user has entered, it makes more sense to use a form. In this case I've used the BeginForm tag helper to generate a suitable HTML <form> tag:
<form asp-action="GetRoomAccessHistory" asp-controller="Files" method="get">
<input type="text" id="createdDate" name="createdDate" placeholder="dd/mm/yyyy" />
<input type="submit" value="Download"/>
</form>
When submitted, this will generate a GET request to the GetRoomAccessHistory action's URL, and append createdDate as a querystring variable, using the value from the textbox.
For Get request,try to use window.location.href.
<input type = "text" id="createdDate" placeholder="dd/mm/yyyy" />
<a onclick = "navigate()" >
< input type="button" value='Download' />
</a>
<script type = 'text/javascript' >
function navigate()
{
var createdDate = document.getElementById('createdDate').value;
var url = "/Files/GetRoomAccessHistory?createdDate=" + createdDate;
window.location.href = url;
}
</script>
And your solution could be simplified to
<form method = "get" asp-controller="Files" asp-action="GetRoomAccessHistory" id="formGetRoomAccessHistory">
<input type = "text" name="createdDate" placeholder="dd/mm/yyyy" />
<button type = "button" onclick="myFunction()">Download</button>
</form>
<script>
function myFunction()
{
document.getElementById("formGetRoomAccessHistory").submit();
}
</script>
<form method="post" class="search-form" action="?">
<fieldset>
<input class="search home_input_search" placeholder="Поиск" type="search" />
<input type="submit" class="subm but_search" value="" />
</fieldset>
</form>
I have a form - search, this is layout and my task consistent in creation link to the controller with params like Products/index?search_name=something. And I dont know how I can transfer value textbox in my link.
Add onsubmit event handler to form, it should:
create Url with query string ?search_name= value from input
set window.location.href to created url
return false
EDIT: Of course, you can implement that in different way, the form is not needed in that case.
You have to give inputs the name they should have on posting and set the right action on the form. The name on the input determines what the key will be in the URL (since you use the GET method). Setting the action on the form will indicate where to send it to.
<form method="post" class="search-form" action="Products/index" method="GET">
<fieldset>
<input name="search_name" class="search home_input_search" placeholder="Поиск" type="search" />
<input type="submit" class="subm but_search" value="" />
</fieldset>
</form>
First of all there it'll be better to call controller paramter "searchName" instead of "search_name". That corresponds with code conventions.
Next, when you call Proudcts/index?search_name=somethink in browser you are initiating GET request. GET requests have no body and communicate with query parameters.
When you create new form and submit 'em to the server you are initiating POST request (by default). Post request has the body-section which contains request parameters.
Then we should start from View. If you want to use query-string you should explicitly create GET-form:
#using (Html.BeginForm("ControllerMethodName", "ControllerName", FormMethod.Get))
{
}
Next you should add name attribute to your input with the same name as in the controller method parameter:
<input class="search home_input_search" name="searchName" placeholder="Поиск" type="search" />
Or you can use HtmlHelper method to generate html:
#Html.TextBox("searchName", string.Empty, new Dictionary<string, object> { { "class", "search home_input_search" }, { "placeholder", "Поиск" } })
Finally you can have as many parameters as you need:
#using (Html.BeginForm("ControllerMethodName", "ControllerName", FormMethod.Get))
{
#Html.Label("Поиск")
#Html.TextBox("searchName", string.Empty, new Dictionary<string, object> { { "class", "search home_input_search" }, { "placeholder", "Поиск" } })
#Html.Label("Включая вложенные")
#Html.CheckBox("includeNested", true)
}
I have an asp.net mvc4 application in which i'd to use the .post ajax's function to post a variable in my view. i had this problem and i posted it here : question, so i'm now trying to solve it by the use of Ajax
View : index.cshtml
<td>
Donner votre avis.
</td>
and
<form method="Post" action="/User/Validate_Expert_Decision" target="_parent">
<span>
<b style="color:red" >
Votre justification *
<b />
<br />
<br />
<textarea rows="10" cols="75" name="justification"></textarea>
</span>
<input type="hidden" name="element" value="#Request.Params["element"]" />
<p>
<input type="submit" name="submit">
<input type="button" name="cancel" value="Annuler" onClick="closebox()">
</p>
</form>
the javascript function
function openbox2(formtitle, fadin) {
var self = $(this);
var arr = self.data('arr');
$.post("/index.cshtml", { element: arr });
var box = document.getElementById('box');
document.getElementById('shadowing').style.display = 'block';
var btitle = document.getElementById('boxtitle');
btitle.innerHTML = formtitle;
if (fadin) {
gradient("box", 0);
fadein("box");
}
else {
box.style.display = 'block';
}
}
controller : Validate_Expert_Decision
public ActionResult Validate_Expert_Decision()
{
string id_element = Request.Params["element"];
return RedirectToAction("Display_Task_List", new { id_project = id_project});
}
the problem is that i always get an empty value of id_element in string id_element = Request.Params["element"];.
What are the reasons of this error? How can i fix it?
If you want to post an ajax request you must use urls in this pattern:
/Area/Controller/Action
in your ajax request you specify your view name, but url for ajax request must be:
$.post("#Url.Action("ActionName, ControllerName, new { Area = "AreaName" }")", { element: arr });
and if you don't have area, just remove last argumant.
Instead of Request.Params["element"] you can easily get your variables by argumant in your action method:
public ActionResult Validate_Expert_Decision(string element)
** If you want to learn ASP.Net MVC i suggest you to read this book:
Pro ASP.Net MVC 4
This is one of best books that i have read until now
What I am trying to do is to open up a jquery dialog.
What is happening is that I see the following html text vs the rendering of the form when it tries to open up the PartialView:
<form action="/Plt/FileUpload" method="post"><input data-val="true" data-val-number="The field PlNum must be a number." data-val-required="The PlNum field is required." id="PlNum" name="PlNum" type="hidden" value="36028" /> <div id="errMsg" >
</div>
<p>File upload for Pl# 36028</p>
<input type="file" name="file" />
<input type="submit" value="OK" />
</form>
Here is the controller action:
public ActionResult FileUpload(int id)
{
var model = new FileUpload { PlNum = id };
return PartialView(model);
}
This is what the view looks like for the PartialView:
#model Ph.Domain.Lb.Models.FileUpload
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
#using (Html.BeginForm("FileUpload", "Plts", FormMethod.Post, null))
{
#Html.HiddenFor(a => a.PlNum)
<div id="errMsg" >
#if (TempData["ErrMessage"] != null)
{
#TempData["ErrMessage"]
}
</div>
<p>File upload for Pl# #Model.PlNum</p>
<input type="file" name="file" />
<input type="submit" value="OK" />
}
This is what my ajax call looks like:
var url = '#Url.Action("FileUpload", "Plt")' + '?id=' + encodeURIComponent(rowid);
$.ajax({
url: url,
type: 'GET',
success: function(result) {
if (result.success) {
$('#dialog').dialog('close');
} else {
// refresh the dialog
$('#dialog').html(result);
}
}
To recap, the ajax call does reach the ActionResult but not sure when it tries to show the partial view it shows HTML vs the rendered html.
The issue here is that you are trying to load razor view which has not been rendered into the dialog's innerHTML. Instead what you should be doing is setting href property of the dialog to the URL.Action link, when creating the dialog. See the link below for an example.
http://www.matthidinger.com/archive/2011/02/22/Progressive-enhancement-tutorial-with-ASP-NET-MVC-3-and-jQuery.aspx
The other option, which is not very maintainable IMO, but which will work with way you are currently doing, is to return the raw HTML from the action method.
I think the first solution is better because the controller is not polluted with HTML string concatenation.
jQuery won't let you use a script inside .html(). You can do this by two ways:
Native DOM HTML injection instead:
$('#dialog')[0].innerHTML = result;
.
Or, setting it as a data attribute and loading it manually:
In view:
<form action="/Plt/FileUpload" ...
data-script="#Url.Content("~/Scripts/jquery.validate.min.js")"
... />
In JS:
$('#dialog').html(result);
var dialogScript = $('#dialog').children().first().data("script");
if(!!dialogScript) { $.getScript(dialogScript); };
Reference: http://api.jquery.com/jQuery.getScript/
.
Another way is use the load method, as in:
$("#dialog").load(url, null, function() {
// on a side note, put $("#dialog") in a variable and reuse it
$("#dialog").dialog();
});
Reference: http://api.jquery.com/load/
.
In the very case of jQuery validation, I'd consider adding it to the parent page itself. You'd expect it to be used in fair number of situations.
I am developing asp.net mvc application. I have a section on the form where I add some text boxes dynamically when the user clicks a "Add New Part" button. The problem is when I submit the form I don't get the data from the fields I added dynamically. I am passing the FormCollection to my controller and stepping through the code in the debugger and those fields are not there. If I look at them in firebug I see them just fine. Any ideas?
Here is the javascript for adding the text fields to the page:
function moreFields() {
var newFields = document.getElementById('readrootpu').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i = 0; i < newField.length; i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName;
}
var insertHere = document.getElementById('newpartusageitems');
insertHere.parentNode.insertBefore(newFields, insertHere);
}
Here is the html:
<div id="readrootpu" class="usedparts" style="display: none">
<% var fieldPrefix = "PartUsage[]."; %>
Part ID:
<%= Html.TextBox(fieldPrefix + "ID", "")%>
Serial Number:
<%= Html.TextBox(fieldPrefix + "Serial", "")%>
Quantity:
<%= Html.TextBox(fieldPrefix + "Quantity", "") %>
<input type="button" value="Remove" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
</div>
When I inspect the html with firebug it looks fine to me:
Part ID: <input type="text" name="PartUsage[].ID" id="PartUsage[]_ID" value="" />
Serial Number: <input type="text" name="PartUsage[].Serial" id="PartUsage[]_Serial" value="" />
Quantity: <input type="text" name="PartUsage[].Quantity" id="PartUsage[]_Quantity" value="" />
Thoughts?
Verify with Firebug that all the post data is being sent from the page via the "Net" tab.
Also, i agree with Kobi: you need to increment the ID's on the cloned elements so they are unique.
I would suggest you look into jQuery for dynamically creating html elements. I have only just started learning jQuery and its very easy.
The following code demonstrates a simple file upload form that allows the user can add more input elements dynamically. Each time the jQuery adds a new input element, i append a chr to the id attribute so they are all unique. Hopefully this helps you:
The script block for the jQuery.. notice the last part is for the ajax animation. The actual copying code is only those 4 lines from $("#moreFiles").click
<script type="text/javascript">
var counter = "oneFile";
$(document).ready(function() {
$("#moreFiles").click(function() {
var newCounter=counter+"1";
$("p#"+counter).after("<p id='"+newCounter+"'><input type='file' name='"+newCounter+"' id='"+newCounter+"' size='60' /></p>");
counter=newCounter;
});
$("#submitUpload").click(function() {
$("#submitUpload").val("Uploading...");
$("img.uploadingGif").show();
});
});
</script>
..and the aspnet markup:
<% string postUrl = Model.PostUrl + (Model.ModelID > 0 ? "/" + Model.ModelID.ToString() : ""); %>
<form id="uploadForm" class="uploadForm" action="<% =postUrl %>"
method="post" enctype="multipart/form-data">
<label>Select file(s) for upload (size must not exceed
<% =Html.Encode(ServiceConstants.MAX_FILE_UPLOAD_SIZE_INBYTES) %> bytes):</label>
<p id="oneFile"><input type="file" name="oneFile" id="oneFile" size="60" /></p>
<% if(Model.MultipleFiles) { %>
<p><a id="moreFiles" href="#">add more files</a></p>
<input id="MultipleFiles" type="hidden" name="MultipleFiles" value="true" />
<% } %>
<p><%--<input id="submitUpload" type="submit" value="Upload" />--%>
<% =Html.InputSubmit("Upload","submitUpload") %>
<% =Html.LoadingImage("uploadingGif") %>
</form>
..this all only boils down to a few lines of html and jQuery.
When you have multiple values on fields with same names, you should be able to see them on the server side using Request.Form.GetValues("key").
You should note that when you clone the nodes, you create copies with the same IDs, which is considered invalid.
Also, you have a for loop there, and I don't quite get what it does (reads the node's name and sets it back - what is the reason for doing that? Should that be var theName = newFields[i].name ?)
I was working with plain HTML when my form worked fine if all the fields were left blank, but it would not submit if I filled out the form.
Later I realized that it was because of a text-field entry 'Email' in which I was entering an email-address containing the character '#'. When I removed the '#', the form started submitting again.
You cannot just aribtrarily add text boxes client-side without having the corresponding server-side controls ready to read the data from the postback. However, you should be able to read the raw data from HttpRequest.Form.
update: oops! it's MVC. I didn't read^H^H^H^H see that. never mind.
-Oisin