Get a non-id form with HTML-UNIT C# - c#

So I've got a HtmlPage with 2 forms in it, not one of those have Id to get.
I've tried to get them by getting the last child on the body (which is the form I need to get), I've been trying to receive it on a HTMLFORM element, but no luck. Any ideas?
Edit:
I'm adding the part of the code you can see :(
<table width="650" bordercolor="#cccccc" bgcolor="white" border="1">
<tbody>
<tr>
<th>
<font size="1">ACCION </font>
</th>
<th>
<font size="1">ESTADO </font>
</th>
<th>
<font size="1">DESCRIPCION </font>
</th>
<th>
<font size="1">CANTIDAD </font>
</th>
</tr>
<form action="le_02pre_deim_anticipada.asp?submit=AA" method="post"></form>
<input name="cod_estado" type="hidden" value="100">
<input name="descrip" type="hidden" value="100">
<input name="buzon" type="hidden" value="B1_">
<input name="filtro_fecha" type="hidden" value="1">
<tr>
<td width="20%" align="CENTER">
<input name="SUBMIT" type="SUBMIT" value="SELECCIONAR"></td>
<td width="10%" align="CENTER">
<font size="2">100</font>
</td>
<td width="60%">
<font size="2">
Informadas en espera de la presentación en Bancos
</font>
</td>
<td width="10%" align="CENTER">
<font size="2">233</font>
</td>
</tr>
<form action="le_02pre_deim_anticipada.asp?submit=AA" method="post"></form>
<input name="cod_estado" type="hidden" value="200">
<input name="descrip" type="hidden" value="200">
<input name="buzon" type="hidden" value="B2_">
<input name="filtro_fecha" type="hidden" value="1">
<tr>
<td width="20%" align="CENTER" bgcolor="#cccccc">
<input name="SUBMIT" type="SUBMIT" value="SELECCIONAR"></td>
<td width="10%" align="CENTER" bgcolor="#cccccc">
<font size="2">200</font>
</td>
<td width="60%" bgcolor="#cccccc">
<font size="2">
Presentadas en entidades recaudadoras en espera de la Solicitud de Levante
</font>
</td>
<td width="10%" align="CENTER" bgcolor="#cccccc">
<font size="2">194</font>
</td>
</tr>
</tbody>
</table>
So I need to send this values through post.
<input name="cod_estado" type="hidden" value="200">
<input name="descrip" type="hidden" value="200">
<input name="buzon" type="hidden" value="B2_">
<input name="filtro_fecha" type="hidden" value="1">
I'm receiving the body on:
HtmlBody body0 = (HtmlBody)P0.Body;

I solved it :D
I just wanted to let you know how I solved this issue.
Not one element on the page has ID, but you can use the position of some markers to navigate it.
HtmlForm f02Submit = PageDecla.Forms[1];
HtmlSubmitInput SubM02 = (HtmlSubmitInput)PageDecla.GetElementsByName("SUBMIT")[1];
f02Submit.AppendChild(SubM02);
var count = f02Submit.ChildElementCount;
SubM02 = (HtmlSubmitInput)f02Submit.ChildNodes[count-1];
PaginaDecla = (HtmlPage)SubM02.Click();
f02Submit = null;
SubM02 = null;
int f = 0, hfImp = 0;
f = PaginaDecla.Forms.Count;
for (int i = 0; i < f; i++)
{
var form = PageDecla.Forms[i];
hfImp = form.ChildElementCount;
SubM02 = (HtmlSubmitInput)PageDecla.GetElementsByName("SUBMIT")[i];
for (int j = 0; j < hfImp; j++)
{
var hfI = (HtmlHiddenInput)form.ChildNodes[j];
var nameHF = hfI.NameAttribute;
var val = hfI.ValueAttribute;
if ((val == cod_int) && (nameHF == name))
{
form.AppendChild(SubM02);
hfImp = form.ChildElementCount;
var btn = (HtmlSubmitInput)form.ChildNodes[hfImp-1];
PageDecla = (HtmlPage)btn.Click();
j = hfImp;
i = f;
}
}
}
Thanks for those who tried, I know I did not provide that much information.

Related

Object reference not set to an instance of an object when posting files using HttpPostedFileBase[]

I am getting an error message - Object reference not set to an instance of an object. I believe that 'files' is empty - but not sure why. Could someone tell me why files would be empty?
Thanks!
View:
<form type="multipart/form-data" action="#Url.Action("AddImage", "HelpDesk")" method="post">
<table cellpadding="0" cellspacing="0" style="width: 100%">
<tr>
<td style="width: 105px"><br /></td>
<td> </td>
</tr>
<tr>
<td style="width: 105px; font-weight: bold">Attach File(s):</td>
<td> </td>
</tr>
<tr>
<td>
<input type="hidden" id="id" name="id" value=#item.ID>
<input type="hidden" id="requesttype" name="RequestType" value=#item.RequestType>
<input type="file" id="files" name="files" multiple>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Add">
</td>
<td> </td>
</tr>
</table>
</form>
Controller:
public ActionResult AddImage(HelpdeskImage model, int id, string requesttype, HttpPostedFileBase[] files)
{
foreach (HttpPostedFileBase file in files)
{
var fileBytes = new byte[file.ContentLength];
file.InputStream.Read(fileBytes, 0, file.ContentLength);
hd.HelpdeskImages.Add(new HelpdeskImage
{
HelpdeskNum = id,
DocumentExt = Path.GetExtension(file.FileName),
Image = fileBytes,
DocumentName = System.IO.Path.GetFileName(file.FileName),
RequestType = requesttype,
Created = DateTime.Now,
}
);
hd.SaveChanges();
}
//}
return RedirectToAction("Details", new { id = id });
}
Modify your form tag to include enctype="multipart/form-data". Specifying this type is necessary when you have an input type="file".
<form enctype="multipart/form-data" action="#Url.Action("AddImage", "HelpDesk")" method="post">
...
</form>

Iterate through a table and get the value in asp.net core using jquery

I am trying to iterate through a table to get the input value. How can I do that ?
tried looping and iterating over the tr and class names. console.log showing nothing for the moment.
CSHTML
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.PositionDebit)
</td>
<td class="Debit">
<span>#item.Debits</span>
<input class="Debits" type="number" value="#item.Debits" />
</td>
<td class="CoefPonderation">
<span>#item.CoefficientDePonderation</span>
<input class="CoefPonderation" type="number" value="#item.CoefficientDePonderation" />
</td>
<td class="Jauge">
<span>#item.Jauge</span>
<input class="Jauge" type="number" value="#item.Jauge" />
</td>
</tr>
}
</tbody>
Javascript
The id of the table is tblDebit
$("#tblDebit tr").each(function () {
var debit = {};
debit.Debits = $(this).find(".Debits").html();
debit.CoefPonderation = $(this).find(".CoefPonderation").html();
debit.Jauge = $(this).find(".Jauge").html();
console.log(debit.Debits);
console.log(debit.CoefPonderation);
alert(debit.CoefPonderation);
debits.push(debit);
});
Hi you have some issues here:
First use .val() instead of .html().
you should use the class CoefPonderation in your td or input not both.
in your loop get each element and dont use this.
here is the javascript code:
$("#tblDebit").find("tbody").children("tr").each(function(index, element) {
let debits = [],
debit = {};
debit.Debits = $(element).find(".Debits").val();
debit.CoefPonderation = $(element).find(".CoefPonderation").children('input[type="number"]').val();
debit.Jauge = $(element).find(".Jauge").val();
// console.log(debit.Debits);
// console.log(debit.CoefPonderation);
console.log('row:' + $.trim($(element).find("td").first().text()) + ', debit:' + debit.Debits + ', ponderation:' + debit.CoefPonderation);
debits.push(debit);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tblDebit" border="1">
<thead>
<th>row</th>
<th>Debits</th>
<th>Ponderation</th>
<th>Jauge</th>
</thead>
<tbody>
<tr>
<td>
1
</td>
<td class="Debit">
<span>item 1</span>
<input class="Debits" type="number" value="1" />
</td>
<td class="CoefPonderation">
<span>ponderation 1</span>
<input class="CoefPonderation" type="number" value="1" />
</td>
<td class="Jauge">
<span>Jauge 1</span>
<input class="Jauge" type="number" value="1" />
</td>
</tr>
<tr>
<td>
2
</td>
<td class="Debit">
<span>item 2</span>
<input class="Debits" type="number" value="2" />
</td>
<td class="CoefPonderation">
<span>ponderation 2</span>
<input class="CoefPonderation" type="number" value="2" />
</td>
<td class="Jauge">
<span>Jauge 2</span>
<input class="Jauge" type="number" value="2" />
</td>
</tr>
</tbody>
</table>
Hope it helps
Instead of html() use val()
debit.Debits = $(this).find(".Debits").val();
debit.CoefPonderation = $(this).find(".CoefPonderation").val();
debit.Jauge = $(this).find(".Jauge").val();

Cannot add textbox with button click in jQuery

I want to add text box in table > td where checkbox is checked, but not working. How can I do this? I'm new to jQuery.
This is my code html:
<table id="list_lab" class="checkbox-inline">
<tr>
<td><input id="list_lab_0" type="checkbox" name="list_lab$0" checked="checked" value="Electrolyte (Lab)"><label for="list_lab_0">Electrolyte (Lab)</label></td>
</tr><tr>
<td><input id="list_lab_1" type="checkbox" name="list_lab$1" checked="checked" value="Creatinine (plus eGFR)"><label for="list_lab_1">Creatinine (plus eGFR)</label></td>
</tr><tr>
<td><input id="list_lab_2" type="checkbox" name="list_lab$2" value="Blood Urea Nitrogen"><label for="list_lab_2">Blood Urea Nitrogen</label></td>
</tr><tr>
<td><input id="list_lab_3" type="checkbox" name="list_lab$3" value="Complete Blood Count"><label for="list_lab_3">Complete Blood Count</label></td>
</tr><tr>
<td><input id="list_lab_4" type="checkbox" name="list_lab$4" value="Dengue NS1 Ag"><label for="list_lab_4">Dengue NS1 Ag</label></td>
</tr><tr>
<td><input id="list_lab_5" type="checkbox" name="list_lab$5" value="Influenza A/B A/(H1N1) Screening"><label for="list_lab_5">Influenza A/B A/(H1N1) Screening</label></td>
</tr><tr>
<td><input id="list_lab_6" type="checkbox" name="list_lab$6" value="Urine Exam"><label for="list_lab_6">Urine Exam</label></td>
</tr>
And this is my script:
$(document).ready(function(){
$('#btn_check').click(function () {
var length = 0;
$('#list_lab').find('tr').each(function(){
var row = $(this);
if(row.find('input[type="checkbox"]').is(':checked')){
$('#list_lab').find(td).append('<input type="text" name="mytext[]" id="txt_row '" + length + "'" />')
}
length++;
});
});
});
Here's working code. Click the button below to run it.
This line:
$('#list_lab').find(td).append('<input type="text" name="mytext[]" id="txt_row '" + length + "'" />')
should have been:
$('#list_lab').find('td').append('<input type="text" name="mytext[]" id="txt_row_"' + length + '" />');
$(document).ready(function() {
function create_inputs() {
var length = 0;
$('#list_lab').find('tr').each(function() {
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked')) {
// first check if you've already added an input to this row
if ($(this).find('input[type="text"]').length == 0) {
$(this).find('td').append('<input type="text" name="mytext[]" id="txt_row_"' + length + '" />');
}
} else {
// if this is not checked, then remove any inputs that you might have added
$(this).find('input[type="text"]').remove();
}
length++;
});
}
// set this to run whenever you click a checkbox
$('input[type="checkbox"]').click(function() {
create_inputs();
});
// and also run once when you first load
create_inputs();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="list_lab" class="checkbox-inline">
<tr>
<td>
<input id="list_lab_0" type="checkbox" name="list_lab$0" checked="checked" value="Electrolyte (Lab)">
<label for="list_lab_0">Electrolyte (Lab)</label>
</td>
</tr>
<tr>
<td>
<input id="list_lab_1" type="checkbox" name="list_lab$1" checked="checked" value="Creatinine (plus eGFR)">
<label for="list_lab_1">Creatinine (plus eGFR)</label>
</td>
</tr>
<tr>
<td>
<input id="list_lab_2" type="checkbox" name="list_lab$2" value="Blood Urea Nitrogen">
<label for="list_lab_2">Blood Urea Nitrogen</label>
</td>
</tr>
<tr>
<td>
<input id="list_lab_3" type="checkbox" name="list_lab$3" value="Complete Blood Count">
<label for="list_lab_3">Complete Blood Count</label>
</td>
</tr>
<tr>
<td>
<input id="list_lab_4" type="checkbox" name="list_lab$4" value="Dengue NS1 Ag">
<label for="list_lab_4">Dengue NS1 Ag</label>
</td>
</tr>
<tr>
<td>
<input id="list_lab_5" type="checkbox" name="list_lab$5" value="Influenza A/B A/(H1N1) Screening">
<label for="list_lab_5">Influenza A/B A/(H1N1) Screening</label>
</td>
</tr>
<tr>
<td>
<input id="list_lab_6" type="checkbox" name="list_lab$6" value="Urine Exam">
<label for="list_lab_6">Urine Exam</label>
</td>
</tr>
</table>
<button id="btn_check">click me</button>

Create a view inside a view on submit MVC4

I have a view with a form, when that form is submitted I want to show another view inside the first view. I have tried with partialview (not sure that is for my purpose?) but I cant get it to work because the model is null (its strongly-typed partialview). But I just want it to be created on the submitbutton and then it should be OK.
So, help my create a view/partialview inside a when submitting my form. Right now I get "Object reference not set to an instance of an object." on the foreach loop in my partial view, but it's not supposed to be created until the form is submitted.
My view:
<div class="calcInput">
#using (Html.BeginForm("ShowDetail", "Calculation"))
{
<div class="calculateBox">
<label for="calcOption">Choose value to calculate:</label>
<select form="anFormCalcInput" id="calcOption" title="Choose what value you want to calculate">
<option value="anPMT">Payment (PMT)</option>
<option value="anI">Interest (I)</option>
<option value="anFV">Future value (FV)</option>
<option value="anPV">Present value (PV)</option>
</select>
</div>
<div class="calculateBox" background-color="#777777">
#Html.Label("Present value (PV)")
#Html.TextBox("PresentValue")
#Html.Label("Future value")
#Html.TextBox("FutureValue")
#Html.Label("Interest rate")
#Html.TextBox("InterestRate") <br />
<input type="radio" name="advanceOrArrears" id="inAdvance" value="inAdvance" /> In advance<br />
<input type="radio" name="advanceOrArrears" id="inArrears" value="inArrears" /> In arrears
</div>
<div class="calculateBox">
<label for="startDate">Start date:</label>
<input type="date" id="anStartDate" name="startdate" title="Choose start date for your calculation" /><br />
#Html.Label("Payment frequency")
<select form="anFormCalcInput" id="anPmtFreq" title="Choose the payment frequency, for example: Every month">
<option value="Monthly">Monthly</option>
<option value="Quarterly">Quarterly</option>
<option value="Yearly">Yearly</option>
</select><br /><br />
#Html.Label("No of payment periods")
#Html.TextBox("PaymentPeriods")
#Html.Label("Date time convention")
<select form="anFormCalcInput" id="anDTC" title="Choose your Date time convention">
<option value="360360">360/360</option>
<option value="365365">365/365</option>
</select><br /><br />
<input type="submit" id="anCalcBtn" class="calcBtn" name="anSubmitBtn" value="Calculate" title="Calculate your calculation" />
</div>
}
</div>
<table cellspacing="0" width="80%">
<div class="calcGraph">
</div>
<div class="calcDetail" id="anCalcDetail">
#Html.Partial("ShowDetail") //This is where I want my view/partialview to show up
</div>
My partialview:
#model IEnumerable<CalcFactory.Models.Calculation>
<table cellspacing="0" width="80%">
<thead>
<tr>
<th>
Date
</th>
<th>
Invoice amount
</th>
<th>
Interest rate
</th>
<th>
Interest amount
</th>
<th>
Amortization
</th>
<th>
Capital balance
</th>
<th></th>
</tr>
</thead>
<tr>
<td align="center">
</td>
<td align="center">
</td>
<td align="center">
</td>
<td align="center">
</td>
<td align="center">
</td>
<td align="center" id="startValue">
</td>
</tr>
#foreach (var item in Model) { //this is where i get null exception, model is null. But it supposed to be created on submit button...
<tr>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
<td>
#Html.DisplayFor(modelItem => item.InvoiceAmount)
</td>
<td>
#Html.DisplayFor(modelItem => item.InterestRate)
</td>
<td>
#Html.DisplayFor(modelItem => item.InterestAmount)
</td>
<td>
#Html.DisplayFor(modelItem => item.Amortization)
</td>
<td>
#Html.DisplayFor(modelItem => item.PresentValue)
</td>
</tr>
}
My Controller:
public class CalculationController : Controller
{
public PartialViewResult ShowDetail(FormCollection form)
{
List<Calculation> cList = new List<Calculation>();
Calculation calc = new Calculation();
calc.Date = Convert.ToDateTime(form["startdate"]);
calc.InvoiceAmount = 2000;
calc.InterestRate = Convert.ToDouble(form["InterestRate"]);
calc.InterestAmount = (Convert.ToDouble(form["PresentValue"]) * Convert.ToDouble(form["InterestRate"]) / 360 * 30);
calc.Amortization = (2000 - (Convert.ToDouble(form["PresentValue"]) * Convert.ToDouble(form["InterestRate"]) / 360 * 30));
calc.PresentValue = Convert.ToDouble(form["PresentValue"]) - calc.Amortization;
cList.Add(calc);
for (int i = 0; i < Convert.ToInt32(form["PaymentPeriods"]); i++)
{
Calculation calcBefore = cList.Last();
calc = new Calculation();
calc.Date = calcBefore.Date.AddMonths(1);
calc.InvoiceAmount = 2000;
calc.InterestRate = Convert.ToDouble(form["InterestRate"]);
calc.InterestAmount = (calcBefore.PresentValue * Convert.ToDouble(form["InterestRate"]) / 360 * 30);
calc.Amortization = (calc.InvoiceAmount - (calcBefore.PresentValue * calc.InterestRate / 360 * 30));
calc.PresentValue = calcBefore.PresentValue - calc.Amortization;
cList.Add(calc);
}
return PartialView("ShowDetail", cList);
}
}

How to get something like "descendant-AND-self::" to htmlNode

I parse from this html table:
<table align="center">
<tbody>
<!-- riadok -->
<tr>
<td valign="middle" align="right">
<form action="130427_0i.htm" method="get">
<input type="submit" class="button" title="uvedení do první modlitby dne" value="Inv.">
</form>
</td>
<td valign="middle" align="center">
<form action="130427_0c.htm" method="get">
<input type="submit" class="button" title="modlitba se čtením" value="Čtení">
</form>
</td>
<td valign="middle" align="left">
<form action="130427_0r.htm" method="get">
<input type="submit" class="button" title="ranní chvály" value="Ranní chvály">
</form>
</td>
</tr>
<!-- riadok -->
<tr>
<td valign="middle" align="right">
<form action="130427_09.htm" method="get">
<input type="submit" class="button" title="modlitba dopoledne" value="9h">
</form>
<form action="130427_09d.htm" method="get">
<input type="submit" class="button" title="modlitba dopoledne (žalmy z doplňovacího cyklu)" value="(alt)">
</form>
</td>
<td valign="middle" align="center">
<form action="130427_02.htm" method="get">
<input type="submit" class="button" title="modlitba v poledne" value="12h">
</form>
<form action="130427_02d.htm" method="get">
<input type="submit" class="button" title="modlitba v poledne (žalmy z doplňovacího cyklu)" value="(alt)">
</form>
</td>
<td valign="middle" align="left">
<form action="130427_03.htm" method="get">
<input type="submit" class="button" title="modlitba odpoledne" value="15h">
</form>
<form action="130427_03d.htm" method="get">
<input type="submit" class="button" title="modlitba odpoledne (žalmy z doplňovacího cyklu)" value="(alt)">
</form>
</td>
</tr>
<!-- riadok -->
<tr>
<td align="right">
<form action="130427_0v.htm" method="get">
<input type="submit" class="button" title="nešpory" value="Nešpory">
</form>
</td>
<td valign="middle" align="center">
<form action="130427_0k.htm" method="get">
<input type="submit" class="button" title="kompletář" value="Kompl.">
</form>
</td>
</tr>
<!-- riadok -->
<tr>
<td align="right"></td>
</tr>
</tbody>
</table>
And I need to get every form (with input) in one HtmlNode.
For example this:
<form action="130427_0c.htm" method="get">
<input type="submit" class="button" title="modlitba se čtením" value="Čtení">
</form>
With my code I get only this:
<form action="130427_0c.htm" method="get">
My code:
public static class FromHtmlTableToHtmlNodeList
{
static List<List<HtmlNode>> tableOfNode = new List<List<HtmlNode>>();
public static List<List<HtmlNode>> Do(string htmltable)
{
var doc = new HtmlDocument();
doc.LoadHtml(htmltable);
HtmlNodeCollection rows = doc.DocumentNode.SelectNodes(".//tr");
for (int i = 0; i < rows.Count; i++)
{
int i2 = tableOfNode.Count;
HtmlNodeCollection cols = rows[i].SelectNodes("./td");
for (int j = 0; j < cols.Count; j++)
{
HtmlNodeCollection inCols = cols[j].SelectNodes("./form/descendant-or-self::*");
List<HtmlNode> nextRow = new List<HtmlNode>();
if (inCols != null)
{
for (int k = 0; k < inCols.Count; k++)
{
if (tableOfNode.Count < i2+k + 1)
{
tableOfNode.Add(nextRow);
}
if (tableOfNode[i2 + k].Count < j + 1) tableOfNode[i2 + k].Insert(j, inCols[k]);
}
}
}
}
return tableOfNode;
}
}
I know that problem is there:
HtmlNodeCollection inCols = cols[j].SelectNodes("./form/descendant-or-self::*");
How should XPath looks like for what I want?
The FORM is treated specially by default by the Html Agility Pack. See here why: HtmlAgilityPack -- Does <form> close itself for some reason?
This code should get all the FORM elements:
HtmlDocument doc = new HtmlDocument();
HtmlNode.ElementsFlags.Remove("form");
doc.Load(myTestHtm);
foreach (var v in doc.DocumentNode.SelectNodes("//form"))
{
Console.WriteLine(v.OuterHtml);
}
You're looking for the XPath expression
./form[input]
This returns all <form/> elements including their subtrees which contain at least one <input/> element.

Categories