How to submit a form with hidden fields from an action? - c#

Say I have the following form that's in classic asp:
<form name="impdata" id="impdata" method="POST" action="http://www.bob.com/dologin.asp">
<input type="hidden" value="" id="txtName" name="txtName" />
</form>
I need to simulate the action of submitting the form in asp.net mvc3, but I need to modify the hidden value before submitting. Is it possible to do this from the action or in another way?
What I have so far...
View:
#using (Html.BeginForm("Impersonate", "Index", FormMethod.Post, new { id = "impersonateForm" }))
{
<input id="Impersonate" class="button" type="submit" value="Impersonate" action />
<input type="hidden" value="" id="txtName" name="txtName" />
}
Controller:
[HttpPost]
public ActionResult Impersonate(string txtName)
{
txtName = txtName + "this string needs to be modified and then submitted as a hidden field";
//Redirect won't work needs the hidden field
//return Redirect("http://www.bob.com/dologin.asp");
}
Solution:
Seems that it isn't easy to do this from the controller so I ended up using jQuery. The action returns a JsonResult.
Something like:
<button id="Impersonate" class="button" onclick="Impersonate()">Impersonate!</button>
<form name="impdata" id="impersonateForm" action="http://www.bob.com/dologin.asp">
<input type="hidden" value="" id="txtName" name="txtName" />
</form>
function Impersonate() {
$.ajax({
type: 'POST',
asynch: false,
url: '#Url.Action("Impersonate", "Index")',
data:
{
name: $('#txtName').val()
},
success: function (data) {
$('#txtName').val(data.Name);
$('#impersonateForm').submit();
}
});
Seems to work well...

It is rather hard to redirect to a POST from a POST (relies on HTTP status codes without universal support), and it is impossible from a GET.
The simplest solution is probably a little JavaScript on the result that posts the (new) form.
Thus you action method returns a view with the necessary data in it (passed via the model from the controller) which will include the JavaScript.

You can try something like this(using jquery):
<input id="Impersonate" class="button" type="submit" value="Impersonate" onclick="$('#txtName').val('new value')" />

Related

How to pass textbox value using #Url.Action in ASP.NET MVC Core 2.2

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>

How add params to my form

<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)
}

Mutiple buttons on MVC form - get item id in the action controller

I have a view with a list of items. Each item have a textbox and a button.
What is the best way to get the item id of the button clicked in the controller action?
I need the value from the associated textbox in the controller action, so I do not think I can use action links.
There are a number of ways to do this. Some use javascript, others don't. I personally prefer to NOT use javascript for basic functionality, unless your design is itself javascript based (such as using ajax)
For instance, you can have each item be wrapped in it's own form, with a different submit value. Just be careful not to nest forms, as that's not valid HTML.
For instance:
#using(Html.BeginForm("MyAction", "MyController", new { id=1 })) {
<input type="submit"/>
#Html.TextBox("TheValue", "One")
}
#using(Html.BeginForm("MyAction", "MyController", new { id=2 })) {
<input type="submit"/>
#Html.TextBox("TheValue", "Two")
}
public ActionResult MyAction(int? id, string TheValue) {
// if they click the first one, id is 1, TheValue = "One"
// if they click the second one, id is 2, TheValue = "Two"
}
this answer is using jquery - If you do not know how to add jQuery to your view or just simply do not want to use it let me know and I can re-work the answer
I would do something like this
<li>
<input type="text" id="1" name="1" class="whatever" />
<input type="button" value="CliCk mE" class="myButton" />
</li>
<li>
<input type="text" id="2" name="2" class="whatever" />
<input type="button" value="CliCk mE" class="myButton" />
</li>
<input type="hidden" id="myHiddenText" name="myHiddenText" />
then add this jQuery:
<script>
$(function(){
$('.myButton').click(function(){
// this is how to get the closest textbox
// you didn't show your html , maybe .prev() or .next()
var textValue = $(this).closest("input[type='text']").val();
// this sets your hidden field with the value from desired textbox
$('#myHiddenText').val(textValue);
});
});
</script>
now when you submit this form to server you can just use myHiddenText on the server
public ActionResult Index(string myHiddenText = "")
{
// hidden fields in the HTML form automatically get passed to server on submit
return View();
}
The best option would be to use jquery but if you only want to use c# I would suggest the following:
I imagine you are using some sort of repeating statement (for or foreach) to generate your textboxes, so what I would do is create a form inside that foreach this new form would contain your textbox, and foreach item you would pass the textbox id to the form submit.
something like this pseudo code:
foreach(item in array){
<form action="address/"#item.Id>
<input type="text" value=""/>
<input type="submit" value="submit textbox"/>
</>
}

How to Pass Model from view to Controller

I'm having following view page,
#using (Html.BeginForm())
{
<fieldset class="fs">
#foreach (var item in Model.lstTravelReadyEntities)
{
<label class="Detail1"><b>Associate Id : </b>#item.Var_AssoId </label>
<label class="Detail1"><b>Vertical :</b>#item.Var_Vertical</label>
<label class="Detail1"><b>Visa ValidFrom :</b>#item.Dt_VisaValidFrom </label><br /><br />
<label class="Detail2"><b>Associate Name :</b>#item.Var_AssociateName</label>
<label class="Detail2"><b>Account Name :</b>#item.Var_AccountName</label>
<label class="Detail2"><b>Visa ValidDate :</b>#item.Dt_VisaValidTill</label><br /><br />
<label class="Detail3"><b>Grade HR :</b>#item.Var_Grade</label>
<label class="Detail3"><b>Project Name :</b>#item.Var_Project_Desc</label><br />
}
<h2> Response Details</h2><br />
Supervisor Response :<input type="radio" class="radi"
name="radio" value="yes" onclick="javascript:Getfunc(this.value);">Yes
<input type="radio"
name="radio" value="no"
onclick="javascript:Getfunc(this.value)">No
<div id="es"></div>
<input type="submit" id="insert" value="Submit"
name="Submit" onclick="javascript:InsertDetails(item);"/>
</fieldset>
}
I want pass all the values of this view page to the controller as parameters for inserting these values into the new table.How can i Achieve this?
Use #Html helpers for your controls.
Have a look at this blog entry from Scott Gu. It's about MVC2 but still applies to MVC4.
For a more concrete example, have a look at this question regarding #Html.RadioButtonFor().
Also, I would recommend hooking your events using jquery instead of inline onclick= html attributes.
<script type="text/javascript">
$("form radio").click(function(){ // or whatever selector you need
Getfunc($(this)[0].value);
});
</script>
Finaly, you will need to make sure your #Html.BeginForm posts to an [HttpPost]-decorated action on your controller that takes your Model as parameter.
What is the Problem in Existing code ?
There is no Input Type Text Control in the form and that's the reason information is not being sent to server. TextBox like controls forwards the data for sending the information to Controller Action Method.
Corrective Action
Let's say TextBox is not Required in you case. Then, you can place Hidden Fields for those View Model Properties which are required to be sent to Controller Post Action method.
Example
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post))
{
<fieldset class="fs">
#foreach (var item in Model.lstTravelReadyEntities)
{
<label class="Detail1">
<b>Associate Id : </b>#item.Var_AssoId
</label>
#Html.HiddenFor(i=> item.Var_AssoId) //Added Hidden Field to send this to server
<label class="Detail1">
<b>Vertical :</b>#item.Var_Vertical</label>
#Html.HiddenFor(i => item.Var_Vertical) //When post this Hidden Field will send
<label class="Detail1">
<b>Visa ValidFrom :</b>#item.Dt_VisaValidFrom
</label>
#Html.HiddenFor(i => item.Dt_VisaValidFrom)
<br />
}
<h2>
Response Details</h2>
<br />
</fieldset>
}
For explaining point of view, I excluded some of the controls. Now, You can add Hidden Fields for those Properties which are required to be sent to Action Method.
Also you should use View Models instead of Passing Individual parameter to Action Method.
Hope this will help you.
Hi try like this,
View
#using (Html.BeginForm("SaveAudit", "Controller", FormMethod.Post)
{
}
Controller
[HttpPost]
public ActionResult SaveAudit(AuditModel model, FormCollection collection)
{
}

mvc PartialView with Dialog Partial View showing html

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.

Categories

Resources