How to calculate square of a number? - c#

I have two text boxes. One textbox for input and other for output. when number entered in first textbox by button click then i want to find square of that number in second textbox by clicking Square button. But i am not able to get the desired result. Nothing is displayed in second textbox when Square button is clicked.
Here is Code snippet:
#Html.TextBoxFor(model => model.textBox, new { #readonly = "readonly" })
<br/>
#Html.TextBoxFor(model => model.textBox1, new { #readonly = "readonly" })
<input name="button" type="submit" id="btntwo" value="2" />
<input name="button" type="submit" id="btnthree" value="3" />
<input name="button" type="submit" id="btnfour" value="4" />
<input name="button" type="submit" id="btnSqr" value="Sqr" />
Here is code snippet for controller:
if (button == "Sqr")
{
model.value1 = model.textBox;
model.textBox1 = (float.Parse(model.value1) * float.Parse(model.value1)).ToString();
}
Note: I have only provided the code which is required to solve the issue.

Here is my assumptions of what you are doing "IF You Use Server Side Solution"
public ActionResult FindSquare()
{
SquareModel model = new SquareModel(); // model contains textbox, textbox1
return View(model);
}
And when you submit form on button click
public ActionResult FindSquare(SquareModel model, FormCollection collection)
{
if(!string.IsNullOrEmpty(collection["button"]) && collection["button"].ToString() == "Sqr")
{
double value = Convert.ToDouble(model.textBox);
var result = value * value;
model.textBox1 = Convert.ToString(result);
return View(model);
}
}
Edit:
Remove removeonly from your view page.

Use Client Side Script to do it easily
$('#btntwo').click(function (e) {
var num = parseInt($('#textBox').val());
$('#textBox1').val(num*num);
return false;
});
If you want to continue in server side, you have to remove #readonly =
"readonly".

I suspect the issue you're having is related to the fact you've got two textboxes (textBox and textBox1), and both are read-only. Nothing can be changed, so perhaps the controller is not firing at all?
I'd also be worried your controller implementation is not wired up properly. You've provided too little code to validate the mainstay failure points for postback processing are not the cause.

Related

how to put a bind-value and an onchange in the same input checkbox?

hello community I have a problem putting a bind-value and an onchange shows me the following error:
The attribute 'onchange' is used two or more times for this element. Attributes must be unique (case-insensitive). The attribute 'onchange' is used by the '#bind' directive attribute.
this is my input checkbox:
<div class="form-group col-md-2">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="customSwitch1"
#bind-value="#ProveedorEstadoCarrito.Cotizacion.Aceptada"
#onchange="e => CheckChanged(e)">
<label class="custom-control-label" for="customSwitch1">Aceptada</label>
</div>
</div>
this is the event:
private Boolean Aceptada = false;
private async Task CheckChanged(ChangeEventArgs ev)
{
Aceptada = (Boolean)ev.Value;
ProveedorEstadoCarrito.Cotizacion.Aceptada = Aceptada;
if (Aceptada == true)
{
var httpResponse = await repositorio.Put("api/Cotizacion", ProveedorEstadoCarrito.Cotizacion);
if (httpResponse.Error)
{
await mostrarMensajes.MostrarMensajeError(await httpResponse.GetBody());
}
else
{
navigationManager.NavigateTo("/formulario-cotizacion");
}
}
}
I want the checkbox to be activated with the bind if it was clicked
First off, you usually don't bind to the value attribute. It remains fixed, and when present, and within a form element, it is passed as form data to the server.
What you want is the checked attribute, like the code snippet below demonstrates:
<input type="checkbox" checked="#selected"
#onchange="#((args) => selected = (bool) args.Value)" />
#code {
private bool selected;
}
The above code show how to bind to a check box element. As you can see, the above code creates a two-way data binding, from a variable to the element, and from the element to the variable. The value attribute is involved. The same usage is applicable to the radion button element. Unlike other input elements, both employ the checked attribute, not the value attribute.
You may also use this variation:
<input type="checkbox" #bind="selected" />
which is equivalent to the code above: a checked attribute + onchange event, but the version above can let you solve your issue. Here's how your code may look like:
<input type="checkbox" class="custom-control-input" id="customSwitch1" checked="#ProveedorEstadoCarrito.Cotizacion.Aceptada" #onchange="CheckChanged">
And
private async Task CheckChanged(ChangeEventArgs ev)
{
Aceptada = (Boolean)ev.Value;
ProveedorEstadoCarrito.Cotizacion.Aceptada = Aceptada;
if (Aceptada == true)
{
Hope this helps...
You can't. But you can set checked=ProveedorEstadoCarrito.Cotizacion.Aceptada to update the state of the checkbox, and for the #onchange event do #onchange=CheckChanged and in that method you can set ProveedorEstadoCarrito.Cotizacion.Aceptada = (bool) ev.Value;

ASP .NET MVC Bind to multiple model properties from single element

I would like to bind html data-* attribute to separate property in my model. How to do that?
As you can see here my button is binding to Operation property and I would like to bind data-* to property Data_RemoveAt.
public enum LinkListOperation
{
AddOne,
RemoveOne,
RemoveAll,
Submit,
RemoveAt
}
public class StepThree_Notification_TemplateEmailViewModel
{
public LinkListOperation Operation { get; set; }
[DisplayName("data-removeat")]
public int Data_RemoveAt { get; set; }
}
#using (var form = Html.BeginForm("AcceptTask", "Task", FormMethod.Post))
{
<div>Linki:</div>
for(int i = 0; i < Model.Links.Count; ++i)
{
<div>
#Html.TextBoxFor(f => f.Links[i], new { Name = string.Format("Model.Links[{0}]", i) })
<button value="RemoveAt" type="submit" name="Model.LinkOperation" data-removeat="#i">Remove</button>
</div>
}
<button value="AddOne" type="submit" name="Model.LinkOperation">MORE</button>
<button value="RemoveOne" type="submit" name="Model.LinkOperation">LESS</button>
<button value="RemoveAll" type="submit" name="Model.LinkOperation">REMOVE ALL</button>
<button value="Submit" type="submit" name="Model.Operation">OK</button>
}
If you are not using ajax, what you can do is to wrap your submit button inside a form tag and set the values you want to sent as form fields. You may use hidden fields for that.
for(int i = 0; i < Model.Links.Count; ++i)
{
<div>
#Html.TextBoxFor(f => f.Links[i],
new { Name = string.Format("Model.Links[{0}]", i) })
#using(Html.BeginForm("Remove","Home"))
{
<input type="hidden" name="Operation" value="#Model.Operation" />
<input type="hidden" name="RemoveIndex" value="#i" />
<button value="RemoveAt" type="submit" name="Model.Operation">Remove</button>
}
</div>
}
Assuming your action method looks like this
public ActionResult Remove(string Operation,int RemoveIndex)
{
// to do : return something with the passed in values.
}
If you already have an outer form tag, This approach won't be ideal as nested forms are not a good idea. You may consider using javascript-ajax code to read the data attribute value and send it to server.
You do not need to add the form tag like what i mentioned above. Keep your markup as it is except, we will add a css class to the submit button which we will use later as the jQuery selector.
<button value="RemoveAt" class='removeBtn' data-removeat="#i"
type="submit" name="Model.Operation">Remove</button>
And add this javscript to listen to the click event on the button and read the data attribute value and then make an ajax post call. Assuming you have jQuery library loaded to your page,
$(function(){
$(".removeBtn").click(function(e){
e.preventDefault();
var _this=$(this);
var removeIndex=_this.data("removeat");
var op=_this.attr("name");
var url = "#Url.Action("Remove","Home")";
url=url+"?Operation="+op+"&RemoveIndex="+removeIndex;
$.post(url,function(res){
//do something when a response comes back, may be update the UI/reload the page ?
//window.location.href=window.location.href;
});
});
});

How to conditionally include page elements in form tag

Working in C#, Visual Studio 2012, MVC4 EF.
I have a view that, when a condition is met, I want to be a form. How do I do this without having to have one section with the page elements in a form, and another section with the same page elements not in a form?
Here is my code for the condition:
#if (this.Model.ItemRequestStatusId == Portal.BusinessModel.Entities.ItemRequestStatusId.VendorRepReview
&& this.User.IsInRole("Vendor Rep"))
{
using (Html.BeginForm("Edit", "ItemRequest", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<button id="btn-data-integrity-final-review" class="btn btn-warning pull-right" type="submit">Vendor Review Complete</button>
}
}
else
{
#Html.ActionLink("Edit this request", "Edit", new { id = this.Model.Id }, new { #class = "btn btn-default pull-right" })
}
and then below that condition, I have the page elements/fields. But they currently don't fall within the form (only the submit button is within the form). I want to capture the fields in POST.
The only way to achieve that is to use javascript. For example you could subscribe to the submit event of this form and then clone all the fields into the form before submitting:
$('#formId').submit(function() {
var inputFields = $('#someDivContainingYourInputFields').clone();
$(this).append(inputFields);
});
But a better approach would be to simply organize your markup in such a way that the input fields are inside the form. You could achieve that by moving the form definition outside of the condition and wrap the input fields with it. Only the submit button could stay inside the if.

Grey out button until all text boxes have text in ASP

I am wondering how to gray out a button until all text boxes have text in ASP.NET and or C#. In the image below I want to gray out the commit button. Cheers, Chris!
You can try similar like this
Check for every input element that it has the value or not and make a global variable which would be true when all the inputs value.
Now enable a button when this variable is true.
$('input').keyup(function() {
var isEntryPresent = false;
$('input').each(function() {
if ($(this).val() == '') {
isEntryPresent = true;
}
});
if (isEntryPresent) {
$('#commitInventory').attr('disabled', 'disabled');
} else {
$('#commitInventory').removeAttr('disabled');
}
});
Js Fiddle Demo
You may need to use the more specific input selector if there are any other input elements are present on the page. So you should use the specific selector as per your condition.
You can do this with the "change" event rather than on every single keyup/keydown. Also, you can use a filter to simplify the code for checking for any empty inputs.
View Demo
$(document).ready(function(){
$("input").on("change", function(){
$("#inp-submit").prop("disabled", anyEmptyInputs());
});
});
function anyEmptyInputs(){
var empty = $("input").filter(function() { return this.value === ""; });
return empty.length > 0;
}
Since you have JavaScript tagged here as well as ASP.NET I'm assuming you are doing this on the Client Side also, or can do it on the Client Side, Below you can run the code Live from JSFiddle
Click Here For A Live JsFiddle Demo.
If you run the code on JsFiddle, it basically attaches all the TextBoxes to the "KeyUp" Event and then checks how many TextBoxes are Not Empty comparing it to the count of the Number of Total TextBoxes, if the count of Not Empty matches the count of number of Total TextBoxes then the Commit button is enabled, otherwise its disabled.
The HTML used there are 5 TextBoxes and 1 Button named Commit. If you are running the code below in your own web page. Remember to include JQuery 2.0
<span>TextBox #1</span><input type="text" /><br /><br />
<span>TextBox #2</span><input type="text" /><br /><br />
<span>TextBox #3</span><input type="text" /><br /><br />
<span>TextBox #4</span><input type="text" /><br /><br />
<span>TextBox #5</span><input type="text" /><br /><br />
<input id="btnSubmit" type="button" value="Commit" />
The JQuery/JavaScript that enables and disables the Commit button based on text in the TextBoxes
$(document).ready(function () {
$("input[type=button]").attr("disabled", "disabled");
//This routine attaches the "KEYUP" event to every TextBox
//When the user types each TextBox will be checked every time
//and count which ones are Not Empty, if the count of the Not Empty
//TextBoxes equals that of the count of all TextBoxes then the
//Commit button is Enabled.
$('input:text').keyup(function () {
var isValid = true;
$('input:text').each(function () {
if ($(this).val().length === 0) {
$("input[type=button]").attr("disabled", "disabled");
isValid = false;
return false;
}
if (isValid) {
$("input[type=button]").removeAttr("disabled");
}
});
});

Custom validation attribute is not working for button click

I have created a function for doing on validations on textbox entered value based on selection in drop downlist .. ..suppose If the dropdownlist selected item is amount then the entered value in textbox must be in between 10 t0 20 like this i have got two more validations.. for that purpose, I have got one textbox and one dropdwonlist and one button in my view
when i enter value in textbox as 30 and select the drop downlist item as "Amount" and then click on the submit button, the view is not showing any error message and ( if i left textbox as empty and then press submit button its should show error msg but its not showing) (I have written Custom functions for validating these ones on server side)
I have put a breakpoint at a postValues method but its not hitting ...
for that I have done like this (controller part)
public class CrossFieldsTxtboxesController : Controller
{
public ActionResult Index()
{
var itemsforDropdown = new List<SelectListItem> {
new SelectListItem{ Text = "Amount" , Value = "Amount"},
new SelectListItem{Text= "Pound", Value ="Pound"},
new SelectListItem {Text ="Percent", Value ="percent"}
};
ViewData["Listitems"] = itemsforDropdown;
return View("DdlCrossFields");
}
[HttpPost]
public ActionResult PostValues(CrossFieldValidation model)
{
if (!ModelState.IsValid)
{
return View(model);
}
else
{
return RedirectToAction("DdlCrossFields");
}
}
}
and this is my view part
#model MvcSampleApplication.Models.CrossFieldValidation
#{
ViewBag.Title = "DdlCrossFields";
}
<h2>DdlCrossFields</h2>
#using (Html.BeginForm())
{
<div class ="editor-field">
#Html.TextBoxFor(m => m.TxtCrossField)
#Html.ValidationMessageFor(m=>m.TxtCrossField)
</div>
#Html.DropDownList("Listitems",ViewData["Listitems"] as SelectList)
<input id="PostValues" type="Submit" value="PostValues" />
}
and this is my model part
public class CrossFieldValidation
{
public string DDlList1
{ get; set; }
[Required(ErrorMessage = "Quantity is required")]
[Display(Name= "Quantity:")]
[ValueMustbeInRange]
[NumericAttributes]
public string TxtCrossField
{ get; set; }
}
would any one have any idea why its not working for button click , any suggestions also would be grateful
many thanks..
I don't see any place where you specify an action that should handle POST request (PostValues in your case). You can use an overload of Html.BeginForm and specify POST action name explicitly:
Html.BeginForm("PostValues", "CrossFieldsTxtboxes")
If I'm right, your POST requests go to Index action and therefore ModelState.IsValid is not checked there.
You can use client side validation using jQuery Unobtrusive validation plugin. Please check if you have the following keys in your web.config file:
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
But note that custom validation attributes require additional JavaScript code to work on client.
I dont see where you are actually calling the method when you do the post - do you have a javscript click handler?
You need to have the method and controller you want to go to in your Html.BeginForm() or you can have something like the below in your view:
#Html.ActionLink("Post Values", "PostValues", "CrossFieldsTxtboxesController", null, new { #class = "postValuesButton", onclick = "return false;" })

Categories

Resources