Firing 'click' event on input submit without ID or name? - c#

I am trying to auto-fill a form on a webpage using .NET's web browser int he C# language. I need to fire the submit button but it doesn't have a name or ID, all it has is a type and value.
The type is equal to "submit" and the value is equal to "Sign In"
Heres how I did it for Sign Up:
webBrowser1.Document.GetElementById("email").InnerText = email;
webBrowser1.Document.GetElementById("password").InnerText = password;
webBrowser1.Document.GetElementsByTagName("input")["register"].InvokeMember("click");
But this time, the submit button doesn't have a name, can someone guide me in the right direction to getting an element by its type or even better, value?
HTML:
<form accept-charset="utf-8" method="post">
<div class="field">
<label for="email">Email or Username</label> <span class="required">*</span> <input class="email" id="email" name="email" size="32" type="text">
</div>
<div class="field">
<label for="password">Password</label> <span class="required">*</span> <input id="password" name="password" size="16" type="password">
<p class="tip">I don't know my password</p>
</div>
<div class="field">
<input id="persistent_hidden" name="persistent" type="hidden" value="f"> <input checked="checked" id="persistent" name="persistent" type="checkbox" value="t"> <label for="persistent">Keep me logged in</label>
</div>
<div class="submit">
<input id="redirect_path" name="redirect_path" type="hidden"> <input type="submit" value="Sign In"> or <a class="cancel" href="/">Cancel</a>
</div>
</form>

try :
foreach(HtmlElement elem in webBrowser.Document.getElementByTagName("input")) {
if (elem.GetAttribute("value") == "Sign In") {
elem.InvokeMember("Click");
}
}

Related

Create a Condition For all non empty fields to be ReandOnly - ASP.NET Core 6.0 MVC

I am developing my first web application with ASP.NET Core 6, and I have a form that shows some fields that I already have information inside of my database.
The problem is: these fields needs to be read-only, because my user needs to considerate the information from my database. If is null, then he needs to insert a value.
Here is an example (consider the field with already set readonly). Most of fields will need this code:
<div class="form-group row">
<div class="col-3">
<label for="Renda Bruta">Associado Desde:</label>
<input type="text" class="form-control">
</div>
<div class="col-3">
<label for="Renda Liquida">Cota Capital</label>
<input type="text" class="form-control">
</div>
<div class="col-6" style="text-align:center">
<label for="ServidorPublico">IAP:</label>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Quantidade" value="#Html.DisplayFor(model => model.iAP.QuantidadeProduto)" ReadOnly="readonly"/>
<input type="text" class="form-control" placeholder="Produtos" value=""#Html.DisplayFor(model => model.iAP.Pro)" ReadOnly="readonly"/>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label for="Renda Bruta">Margem Contribuição</label>
<input type="text" class="form-control">
</div>
<div class="col-8" style="text-align:center">
<label for="ServidorPublico">Cheque Especial</label>
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Dias de Utilização" />
<input type="text" class="form-control" placeholder="Valor Utilizado" />
<input type="text" class="form-control" placeholder="Valor Contratado" />
</div>
</div>
</div>
I already build the form, and put some fields readonly with ReadOnly="readonly", but is there a way to loop all fields and put readonly with a loop or I really need to write in all fields the code `ReadOnly="readonly" ? My form is really big
But is there a way to loop all fields and put readonly with a loop or
I really need to write in all fields the code `ReadOnly="readonly" ?
My form is really big
Yes, you can set that ReadOnly attribute based on the value of your textbox field.
In this scenario you have to consider two way, either you should consider your textbox name attribute or type="text" attribute. Upon these two very way we will be decided which textbox set to readonly which is not.
For [type='text'] Attribute:
When [type='text'] means we will check all the textbox type of text and check if the textbox have value and set the readonly attribute:
View:
<div class="form-group row">
<div class="col-3">
<label for="Renda Bruta">Associado Desde:</label>
<input type="text" name="Associado" class="form-control">
</div>
<div class="col-3">
<label for="Renda Liquida">Cota Capital</label>
<input type="text" name="Cota" class="form-control">
</div>
<div class="col-6" style="text-align:center">
<label for="ServidorPublico">IAP:</label>
<div class="input-group mb-3">
<input type="text" name="Quantidade" class="form-control" placeholder="Quantidade" value="Test Value" />
<input type="text" name="Produtos" class="form-control" placeholder="Produtos" value="Test Value Products" />
</div>
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label for="Renda Bruta">Margem Contribuição</label>
<input type="text" name="Margem" class="form-control">
</div>
<div class="col-8" style="text-align:center">
<label for="ServidorPublico">Cheque Especial</label>
<div class="input-group mb-3">
<input type="text" name="Dias" class="form-control" placeholder="Dias de Utilização" />
<input type="text" name="Utili" class="form-control" placeholder="Valor Utilizado" />
<input type="text" name="Contra" class="form-control" placeholder="Valor Contratado" />
</div>
</div>
</div>
Script:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$("input[type='text']").each(function (index, item) {
console.log(item);
if ($(item).val() != "") {
$(item).attr('readonly', true);
}
});
});
</script>
}
Note: When will will set readonly to a textbox which has value based on the text type then we have to consider like input[type='text']
For name Attribute:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$("input").each(function (index, item) {
console.log(item);
if ($(item).val() != "") {
$(item).attr('readonly', true);
}
});
});
</script>
}
Note: Remember in this scenario, you need to set name property for your textbox to identify uniquely as you can see I have added name property
Output:
what I understand that you want to make the input field enterable when the value of it is null. this is done by javascript.
I suggest to make all input fields read only.
use javascript to test each field, if its value is null make it enterable.
for example:
<input type="text" id="text1" class="form-control" placeholder="Quantidade" value="#Html.DisplayFor(model => model.iAP.QuantidadeProduto)" ReadOnly="readonly"/>
<script>
window.onload = function() {
if (document.getElementById("text1").value.length == 0)
{
document.getElementById("text1").readOnly = false;
}}
</script>
so basically when the page is loading the script will check if the input is null or not and it will do the action.

Form fields from the ASP.NET View appear NULL in the Controller

The form fields do not return the value of the form even thought the asp-controller and asp-action is stated.
The form does go to the right controller function and returns the right view, however, it does the form object is NULL.
#using ActionAugerMVC.Models
#model Tuple<IEnumerable<Cities>,Content,IEnumerable<Content>,Quote>
#addTagHelper "*,Microsoft.AspNetCore.Mvc.TagHelpers"
<div class="sidebar__item">
<p class="subheading">Instant Quote Request</p>
<form class="register__form" role="form" asp-controller="Plumbing" asp-action="QuoteForm" method="post">
<div class="text-danger" asp-validation-summary="All"></div>
<div class="form-group">
<label class="sr-only">Full Name </label>
<input asp-for="#Model.Item4.FullName" type="text" class="form-control" placeholder="Full name">
</div>
<div class="form-group">
<label class="sr-only">Your phone</label>
<input asp-for="#Model.Item4.Phone" type="tel" class="form-control" placeholder="Your phone">
<span asp-validation-for="#Model.Item4.Phone" class="text-danger"></span>
</div>
<div class="form-group">
<label class="sr-only">E-mail</label>
<input asp-for="#Model.Item4.Email" type="email" class="form-control" placeholder="E-mail">
<span asp-validation-for="#Model.Item4.Email" class="text-danger"></span>
</div>
<div class="form-group">
<label class="sr-only">Your Message</label>
<input asp-for="#Model.Item4.Message" type="text" class="form-control" placeholder="Your Message">
</div>
<input type="submit" value="Get a Quote Now" class="btn btn-accent btn-block">
</form>
</div> <!-- .sidebar__item -->
And the Controller looks like this, with the Quote object being null.
The hard coded, values appear correctly in the view, but the Quote object returned by the form is null.
[HttpPost]
public IActionResult QuoteForm(Quote quote)
{
if (ModelState.IsValid)
{
/* quote.FullName = "Umar Aftab";
quote.Email = "test#email.com";
quote.City = "Calgary";
quote.Message = "Test Message";
quote.Phone = "6474543769";
*/
}
return View(quote);
}
The issue is your use of a Tuple as your view's model combined with asp-for. For example, with something like:
<input asp-for="#Model.Item4.FullName" type="text" class="form-control" placeholder="Full name">
The name of the input is going to end up as Item4.FullName. However, your action accepts only Quote, which means the modelbinder needs the input to be named just FullName in order to bind it properly. You either need to accept the same model the view uses (though I've never tried posting a Tuple so not sure if that will even work), or you can use a partial view to work around the issue.
Essentially, you just would need to move all the fields related to just Quote to a partial view. Then, in this view, you can include them via:
#Html.Partial("_QuoteFields", Model.Item4)
That should be enough psych Razor out enough to just name the fields like FullName instead of Item4.FullName. If it's not, then you may need to reset the HtmlFieldPrefix, via:
#Html.Partial("_QuoteFields, Model.Item4, new ViewDataDictionary(ViewData) { TemplateInfo = new TemplateInfo { HtmlFieldPrefix = "" } })
The model on your view is different than the model you're trying to bind it to in the controller. You're not going to get the key/value pairs to match up
Put your razor in a partial view with Quote as the model and try that.
_QuoteForm.cshtml
#model Quote
<div class="form-group">
<label class="sr-only">Full Name </label>
<input asp-for="FullName" type="text" class="form-control" placeholder="Full name">
</div>
<div class="form-group">
<label class="sr-only">Your phone</label>
<input asp-for="Phone" type="tel" class="form-control" placeholder="Your phone">
<span asp-validation-for="Phone" class="text-danger"></span>
</div>
<div class="form-group">
<label class="sr-only">E-mail</label>
<input asp-for="Email" type="email" class="form-control" placeholder="E-mail">
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label class="sr-only">Your Message</label>
<input asp-for="Message" type="text" class="form-control" placeholder="Your Message">
</div>
OriginalView.cshtml
using ActionAugerMVC.Models
#model Tuple<IEnumerable<Cities>,Content,IEnumerable<Content>,Quote>
#addTagHelper "*,Microsoft.AspNetCore.Mvc.TagHelpers"
<div class="sidebar__item">
<p class="subheading">Instant Quote Request</p>
<form class="register__form" role="form" asp-controller="Plumbing" asp-action="QuoteForm" method="post">
<div class="text-danger" asp-validation-summary="All"></div>
#Html.Partial("_QuoteForm", Model.Item4)
<input type="submit" value="Get a Quote Now" class="btn btn-accent btn-block">
</form>
</div> <!-- .sidebar__item -->

Form does not submit when I click submit button of it C# & jQuery

I append my select option from database table. Select option has two type
scalar
event
If the option type is scalar, I need to show 2 input fields (alarm, reset) so that user can inset values in it and when the option type is event I need to hide 2 input fields (alarm, reset) so that user cannot inset values in it.
When the option type is scalar, my form saves successfully but when option type is event form submit button not going to perform any action.
Can you please help?
Here is my code
HTML
<div class="row">
<form method="post" action="/Home/SaveTriggers" class="form-inline">
<div class="col-md-12">
<div class="col-md-2">
<select name="sourceId" class="select2" required>
#foreach (var i in ViewBag.opt)
{
<option value="#i.Id,#i.name,#i.type" id="opt">#i.name</option>
}
</select>
</div>
<div class="col-md-2">
<input id="alarm" name="alarm" type="text" placeholder="alarm" style="display:none" required />
</div>
<div class="col-md-2">
<input id="reset" name="reset" type="text" placeholder="reset" style="display:none" required />
</div>
<div class="col-md-1">
<input type="text" name="delay" id="delay" placeholder="delay" required />
</div>
<div class="col-md-3">
<select class="address2" name="action" id="select" required>
<option selected disabled>Select alarm action</option>
<option>John Doe, Switch on warning light</option>
<option>John Doe</option>
<option>Do anything</option>
</select>
</div>
<div class="col-md-2">
<button id="delete2" type="button" class="btn btn-default">Delete</button>
</div>
<button class=" add btn btn-primary" type="submit">Add</button>
</div>
</form>
</div>
Jquery(as i have to hide or show alarm or reset fields respectively)
<script>
$(document).ready(function () {
$(".select2").change(function () {
var text = $(".select2 option:selected").text();
var val = $(".select2 option:selected").val();
var res = val.split(",");
var type = res[2];
if (type == "scalar") {
document.getElementById("reset").style.display = "block";
document.getElementById("alarm").style.display="block"
}
else if(type=="event") {
document.getElementById("reset").style.display = "none";
document.getElementById("alarm").style.display = "none"
var alarm = document.getElementById("alarm");
}
});
});
</script>
The problem is most likely your inputs for alarm and reset.
If type is event, they are hidden and will most likely hold no value. But since they are required, the form will not submit until that error is resolved.
So you can either remove the required attribute from those 2 input fields, populate them with default values or use novalidate in your form tag. This disables form validation. You'd have to validate your inputs by hand in javascript.
<div class="col-md-2">
<input id="alarm" name="alarm" type="text" placeholder="alarm" style="display:none" />
</div>
<div class="col-md-2">
<input id="reset" name="reset" type="text" placeholder="reset" style="display:none" />
</div>
<div class="col-md-2">
<input id="alarm" name="alarm" type="text" placeholder="alarm" style="display:none" required />
</div>
<div class="col-md-2">
<input id="reset" name="reset" type="text" placeholder="reset" style="display:none" required />
as you're having required attribute in your input element, the validation is getting triggered and not letting you submit the form.
i would suggest you to do a validation on jquery on submit instead of using default html5 validation

MVC Basic - how to get html button in URL

I'm new in MVC.
I have simple HTML website where I have two three inputs
input to write email adress
one checkbox
button
I have one HomeController which have on method
[HttpGet]
public ActionResult Index()
{
return View();
}
I want to generate method [HttpPost] after I click the button.
Now after I am click inputbutton in my Url I have just one change
Before click
http://localhost:52254/Home/Index
and after
http://localhost:52254/Home/Index?
There is a form
<form>
<div class="col-xs-3">
<input type="email" class="form-control" id="email" placeholder="Wpisz adres email">
</div>
<br />
<label class="checkbox-inline">
<input type="checkbox" />
</label>
<br />
<a href="/Controller/View">
<input type="submit" value="Sign" class="btn btn-primary"/>
</a>
</form>
Change The Code Like This
#using (Html.BeginForm())
{
<div class="col-xs-3">
<input type="email" class="form-control" id="email" placeholder="Wpisz adres email">
</div>
<br />
<label class="checkbox-inline">
<input type="checkbox" />
</label>
<br />
<a>
<input type="submit" value="Sign" class="btn btn-primary"/>
</a>
}

Button not call post form with Razor C#

I have a page with post and wanted when the user clicks on the button "Atualizar", instead of calling the post, called a JQuery. How to do this?
<form action="/Conselho/Detalhar/6" method="post"> <div class="row">
<h3>Visualizando Conselho Profissional</h3><hr>
<input data-val="true" data-val-number="The field ConselhoID must be a number." data-val-required="O campo ConselhoID é obrigatório." id="ConselhoID" name="ConselhoID" type="hidden" value="6">
<div class="col-md-2">
<label for="Sigla">Sigla</label> <span class="field-validation-valid" data-valmsg-for="Sigla" data-valmsg-replace="true"></span><br>
<input class="form-control" id="Sigla" name="Sigla" type="text" value="CREA"><br>
</div>
<div class="col-md-10">
<label for="Descricao">Descrição</label> <span class="field-validation-valid" data-valmsg-for="Descricao" data-valmsg-replace="true"></span><br>
<input class="form-control" id="Descricao" name="Descricao" type="text" value="Conselho Federal de Engenharia e Agronomia"><br>
</div>
<div class="col-md-5">
<div class="botoes">
<input name="btnSubmit" class="btn btn-success" type="submit" value="Salvar">
<input name="btnSubmit" class="btn btn-warning" type="submit" value="Excluir">
<input name="btnSubmit" class="btn btn-info" type="submit" value="Atualizar">
<a class="btn btn-default" href="/Conselho/Index">Voltar</a> </div>
</div>
</div>
</form>
You should add an id attribute so you have an easy, unique selector for the button. I have given it "Atualizar" in this example
Write a javascript event handler for the button
Prevent default behavior which in this case is form post.
Alternatively, you could use the button tag, and this will not submit the form by default
var doSomething = function(){
//your code here
};
$('#Atualizar').click(function(e) {
e.preventDefault();
doSomething();
});
Alternative:
<button type="button" onClick="doSomething()" id="Atualizar">
In javascript, you can listen for the click event of this specific button, get the form for this button, serialize the form and post it the action method url.
$(function(){
$("#Atualizar").click(function(e){
e.preventDefault(); //prevent default form submit behaviour
var _this=$(this);
var _form=_this.closest("form");
$.post(_form.attr("action"),_form.serialize(),function(res){
// do something with res
});
});
});

Categories

Resources