How to get html hidden field value inside c#? - c#

I used a hidden field inside li tag in c#. please help me to get the value of hidden field in it..
public string text="";
for (var i = 0; i < dt.Rows.Count; i++)
{
text += "<li class=''>";
text += "<input type='hidden' id='hid_dtlid' name='hid_dtlid' value='" + dt.Rows[i]["Spindtlid"].ToString() + "'/>";
text += "</li>";
}

All the name attributes of the hidden field elements should be unique. This can be accessed on the server (provided they are all nested in a html form element). You simply make you use of Request.Form collection.
Say below is what your markup rendered by asp.net looks like
<form method="post" action="foo.aspx">
<!-- other stuff -->
<input type="hidden" name="fooField" value="bar"/>
<!-- more other stuff -->
</form>
Note that this is not an element marked with runat="server". And even if its so, you wouldn't know the difference unless you inspect carefully.
On the server-side you can access it as follows:
var value = Request.Form["fooField"]; //stores "bar"

In jquery it would be:
thevalue = $('#hid_dtlid').val()

If you're loking for server side on postboack Request.Form["hid_dtlid"]
Asp.net is nothing but a series of request and responsonses with some fancy absctration on top. The basics are still accessible through the Request and Response objects

Since you have not added these hidden fields as a C# hidden field object hence they will not be available directly.
However with post back these fields will be sent by the browser client in the header in Request.Form collection which can be extracted like below:
var hiddenElements = Request.Form["hid_dtlid"] ;//it will return an array of fields with name hid_dtlid

As you want to get the cotnrol value directly in c# you need to set runat="server" for that control asp.net web forms.
<input runat="server" type='hidden' id='hid_dtlid' name='hid_dtlid' value='" + dt.Rows[i]["Spindtlid"].ToString() + "' />
when it will post data you can get
var hiddenElements = Request.Form["ID"]

Related

How can I loop through html controls in ASP.NET page with No "runat=server"

How can I loop through html controls inside an ASPX page which don't have "runat=server" attribute?
Because of using code blocks and dynamic variables on them I cannot add the attribute:
<input lang='<%= language.ID %>' checked='<%= check(x) %>' />
How can I loop through html controls inside an ASPX page which don't have "runat=server" ...
Depends on what you want you're looking to do.
As the other answers have stated, end of the day, it's all HTML and therefore a Form will submit (by default an HTTP POST for ASP.Net Web Forms hence Postback) somewhere and you can loop through HttpRequest.Form on the server side (aka "code-behind").
As stated, in the end everything renders as a standard HTML element that you can provide id or class and "loop" through them and do what you want on the front end.
Here's a trivial example:
var eles = document.getElementsByClassName('inputs');
var count = eles.length;
var str = "there are " + count + " elements:<br>";
for (var i = 0; i < count; i++) {
str = str + "name: " + eles[i].name + " id: " + eles[i].id + "<br>";
}
var result = document.getElementById("result");
result.innerHTML= str;
<input name="foo" lang='some-server-generated-string-1' id="ele1" class="inputs" />
<input name="bar" lang='some-server-generated-string-2' id="ele2" class="inputs" />
<p id="result"></p>
Hth.

Duplicate of parameters in URL caused by checkbox

We're having a problem with the following:
If our checkbox is checked, our url has two of the same parameters in it:
http://localhost:63978/Failure?ShowResolvedFailures=true&ShowResolvedFailures=false
We are almost sure that is has to do with the hidden parameter from the checkbox (See: asp.net mvc: why is Html.CheckBox generating an additional hidden input)
The first "ShowResolvedFailures" would be the value which is generated because of the fact that the checkbox is checked.
The second "ShowResolvedFailures" is from the hidden property we expect
But how do we remove that parameter from our url. Of course we do not want to see the hidden parameter in our URL.
Here is our code:
cshtml:
<form asp-controller="Failure" asp-action="Index" method="GET" role="form" id="searchForm" asp-antiforgery="false">
<div class="pull-right">
<span>
Toon opgeloste storingen?
<input asp-for="#Model.ShowResolvedFailures"
type="checkbox"
class="customCheckbox"
onclick="this.form.submit();">
</span>
</div>
controller.cs:
[HttpGet]
public async Task<IActionResult> Index([FromQuery] FailureIndexViewModel requestModel)
{
var showResolvedFailures = requestModel?.ShowResolvedFailures ?? false;
var searchQuery = new FailureSearchQuery
{
CorrelationId = requestModel?.CorrelationId,
CommandId = requestModel?.CommandId,
ShowResolvedFailures = showResolvedFailures
};
var urlWithQueryString = QueryHelpers.AddQueryString(#"api/tool/failures/search", searchQuery.GetQueryParameters());
var failureOverviewModel = await GetDataAsync<FailureOverviewModel>(urlWithQueryString);
return View("Index", new FailureIndexViewModel
{
CorrelationId = requestModel?.CorrelationId,
CommandId = requestModel?.CommandId,
ShowResolvedFailures = showResolvedFailures
});
}
My personal view (may be stupid one) is this is design issue. there are two fields created for check box, one is checkbox itself and other one is hidden input. Hidden input is always false for some reason (that I don't know) and value of check box depends on whether it is checked or not. If it is not checked query string will be false because check box will not send anything if it is unchecked instead value will be of hidden input. But when check box is checked then it will send true and hidden input will send false which is your case. I would use work around for that.
Replace
var showResolvedFailures = requestModel?.ShowResolvedFailures ?? false;
with
var showResolvedFailures = Request.QueryString["ShowResolvedFailures"].Contains("True") ? true : false;
Use your own input checkbox construction instead the asp-for taghelper, This way you won't use the default template for boolean
<input name="#Html.NameFor(m => mShowResolvedFailures)"
type="checkbox"
class="customCheckbox"
onclick="this.form.submit();">

Dynamic textboxes with dropdownlist populated by database

I have a project where I need to provide functionality that allows a user to click a button (1 or more times) to dynamically add 2 textboxes with labels and a dropdownlist populated by a database call each time the button in clicked.
At first I was using jquery to add the 2 textboxes with labels but just had the requirement to add the dropdown populated by a database call.
I was using the following code for the jquery:
<script type="text/javascript">
$(document).ready(function () {
$("#btnAdd").click(function () {
var field = $("#field").val();
var input = "<input name='titles' id='field' type='text' />";
var input2 = "<textarea name='descriptions' id='field' rows='8' columns='80' />";
var newRow = "<tr><td>" + field + "</td><td>" + input + "</td><td>" + input2 + "</td></tr>";
var newRow2 = "<br /><label>Additional Issue: </label><br /><input type='text' size='50' name='addIssue' id='field' value='' /><br /><br /><label>Description:</label><br /><textarea rows='8' cols='80' name='addProblem' id='field' ></textarea><br /><br />"
$('#controls').append(newRow2);
});
});
</script>
That works great. However, I'm struggling with the best way to add in the dropdown, and it can be server side or clientside. I really haven't created asp.net controls dynamically, but I think that would be the way to go.
Any suggestions?
Well, to fit in with the rest of your design, you should probably just do it client side. You can create a select input pretty much just like you're doing your text inputs, then add options using AJAX call to a JSON web method. There are a lot of examples of this online, but here's one and here's another. And here's a third.

c# - Access elements created by jquery in c# method

In a user control I have an unordered list that contains items showing editable file data.
I create these items in my javascript using a JSON string set in a hidden field when the page is loaded or when the controlling element (AJAX async file upload) performs it's OnClient_UploadComplete function.
Everything I have is solid so far: the items are created on the client side, and I can get any values changed using an existing hidden field and transfer the data back to a BL object when I need it.
My problem is that during the server-side On_UploadComplete function, my server code cannot find any of the dinamically created items created by my javascript to add essential data to the new item.
I have to be missing something. The value I get from the control is "/r/n"..
My best guess is that my c# code is set up wrong. On the page, to find the ul I have:
Control m_ulFileItems = m_fuPhotoUpload.FindControl("m_ulFileItems");
I'll do some more loking, but this is an important aspect of getting this control to work.
I do not have any idea how you could be able to access these controls on server side. However, what I would suggest is that you pass their values from client to server, perhaps like this:
$.ajax({
url: ...,
type: ...,
data: ids and values from your controls in json format
});
Here are some more details:
if this is the HTML:
<div>
<div id="placeHolder"></div>
<input type="button" value="Submit" onclick="submit();" />
</div>
And I have added some text boxes the following way:
$(document).ready(function () {
for (var idx = 0; idx < 10; idx++) {
$('<input class="myInput" type="text" />').appendTo($('#placeHolder'));
}
});
Then this should work:
function submit() {
var jsonInput = '{';
var inputList = $(".myInput");
for (var idx = 0; idx < inputList.length; idx++) {
jsonInput = jsonInput + 'txt_' + idx + ': ' + $(inputList[idx]).val() + ',';
}
jsonInput = jsonInput.substring(0, jsonInput.length - 1);
jsonInput = jsonInput + '}';
alert(jsonInput);
$.ajax({
url: "WebForm1.aspx/HandleSubmitClick",
data: jsonInput
});
}
Hope it helps.
If you do not like the Ajax call to the server I can suggest to use a hidden control, and put that string into the hidden control before you go to the server. Then you will be able to take the value of that hidden control on the server side.
Anyway, this is the basic idea - collect and prepare the data on the client side, then send it to the server side somehow.
Add a hidden field to the page and before posting back to the server, scan all the items in the list, maybe create a JSON object which contains all the needed info from the created items, and set the hidden field value to this JSON. Now you should be able to grab that value and parse the JSON in C# and handle it from there.

.NET "Request.Files" capture extra input

I made a dynamically multi upload form with file type inputs. When you select a file new file input will appear. When submit the form all inputs captured by "Request.Files" at code behind.
There is no problem when i generate those file in a .aspx file but when i use Web User Control (.ascx) page "Request.Files" add 1 more request (for the blank file input).
Why ascx count the balnk input?
I share the codes below:
MultiImage.ascx
<ul id="imagesToUpload">
<li><input type="file" class="imageToUpload" runat="server" /></li>
</ul>
<script type="text/javascript">
$('.imageToUpload').live('change', function () {
$(this).parent().append('<div class="imageInfoContainer"><span>Yüklenen görsel: ' + $(this).val() + ' </span><div class="deleteImage">Sil<div><div>');
if ($('input:file').length < <%= MaxImageNumber %>) {
$(this).parent().parent().append('<li><input type="file" class="imageToUpload" runat="server" /></li>');
}
});
$('.deleteImage').live('click', function () {
$(this).parent().parent().remove();
if ($('input:file').length < 1) {
$('#imagesToUpload').html('<li><input type="file" class="imageToUpload" runat="server" /></li>');
}
});
</script>
MultiImage.ascx.cs
var imageCollection = Request.Files; //Counts all file inputs included the blank one
Why ascx count the balnk input?
You mean why does HttpRequest object count that input? Because it is present in the request. You can however easily check if it is empty or not by looking at the HttpPostedFile.ContentLength property of each element inside Files collection.

Categories

Resources