HTML-Razor float as input value - c#

I have this bit of HTML which should call /nodes/calibratePH?value=afloatnumber:
<div style="float:left; width:50%; margin-bottom:30px;">
<h3>PH calibration</h3>
<form id="CalibrationBar" action="/Nodes/CalibratePH" method="post">
<select id=ids type="text" name="name">
<option value="0" disabled selected>name</option>
#{
foreach (var configuration in Program.CAN_Listener.KnownConfigID)
{
if (configuration.type == Web_App.Models.Sensor_Types.PH)
{
<option value="#configuration.name">#configuration.name</option>
}
}
}
</select>
<input type="number" step="0.01" max="10.0" min="-10.0" placeholder="calibration value" name="value">
<input type="submit" value="calibrate PH">
</form>
The problem is, when I enter for instance: 3.09 or 3,09 (doesn't matter). The method CalibratePH in the controller(MVC, ASP.NET) gets the value: 309. 1.1 gives 11, and so forth. Does anyone have an idea how to solve this? I'm thinking about entering the input as text and evaluate the value upon recieval in the method, but that's not how it should be... right?
EDIT:
This guy seems to have sort of the same problem

I suggest you to make the parameter string on method calibratePH and when you receive it then cast it to float number.

Related

How to append a C# formatted html

I have a button that append's the same layout of html but I have a problem taking the select values with it. My html is:
<div id="degreePlusSign">Button</div>
<div class="padding">
<div class="col-md-5 col-xs-12">
<label for="prefix" class="sr-only">Degrees</label>
<select class="form-control marginBottom15">
#{
foreach (var degree in ViewBag.NewDegrees)
{
<option value="#degree.DegreeID" selected>#degree.DegreeName</option>
}
}
</select>
<span class="glyphicon form-control-feedback"></span>
</div>
</div>
JS:
$('#degreePlusSign').on('click', function () {
$(this).closest('.padding').append('<div class="padding mBottom"><i class="fa fa-times-circle fa-2x" aria-hidden="true"></i><div class="col-md-5 col-xs-12"><select class="form-control marginBottom15">#{foreach (var degree in ViewBag.NewDegrees){<option value="#degree.DegreeID" selected>#degree.DegreeName</option>}}</select><span class="glyphicon form-control-feedback"></span></div><div class="col-md-7 col-xs-12"><input class="form-control" placeholder="Major/Area of Study" type="text" /></div></div>');
});
Basically it recreates the html, but my problem is I'm using a foreach loop to bring in the values from the backend and it will only work with the inital container, not the duplicated containers afterwards. How do I keep the values on every duplication with the append jquery?
You have got two options:
Spit options values (formatted) from C# and keep in a JS variable:
{
var opts=new StringBuilder();
var sel="selected";
foreach(var d in ViewBag.NewDegrees)
{
opts.Append($"{d.DegreeName}");
sel="";
}
}
Then somewhere down store it into a js variable:
var optsList="#(opts)";
Now you can use append new HTML as:
$('#degreePlusSign').on('click', function () {
$(this).closest('.padding').append('<div class="padding mBottom"><i class="fa fa-times-circle fa-2x" aria-hidden="true"></i><div class="col-md-5 col-xs-12"><select class="form-control marginBottom15">'+
optsList/*THIS IS THE VALUE WE STORED FROM C# CODE*/
+'</select><span class="glyphicon form-control-feedback"></span></div><div class="col-md-7 col-xs-12"><input class="form-control" placeholder="Major/Area of Study" type="text" /></div></div>');
});
Clone the generated select element and use that:
$('#degreePlusSign').on('click', function () {
/*CLONE EXISTING SELECT ELEMENT. YOU MAY WANT TO PUT AN ID FOR SELECTION*/
var cl=$("select.form-control.marginBottom15").clone();
var d = $("").addClass("padding mBottom")
append("").addClass("fa fa-times-circle fa-2x").attr("aria-hidden",'true');
/*APPEND CLONED SELECT TO INNER DIV*/
d.append("").addClass("col-md-5 col-xs-12").append(cl);
d.append(cl);
d.append("").addClass(glyphicon form-control-feedback");
d.append("").addClass("col-md-7 col-xs-12").append("").addClass("form-control")
.attr("placeholder","Major/Area of Study").attr("type","text");
$(this).closest(".padding").append(d);
});`
Hope you will be able fix any jQuery mess. I haven't used it since long.
.clone was what I was looking for. $('.padding').clone().append('.padding');

How to overwrite one model property in ASP.Net core

I have a model with say 10 properties. A, B, C and so on...
Property A is an array.
For each value in array I generate one tag like this:
<div class="col-sm-10 row">
#foreach (var item in Model.A)
{
<div class="col-sm-1 right-buffer">
<i class="" aria-hidden="true">#item.Text</i>
</div>
}
</div>
When user clicks on some link I should redirect it to the same page, but with Some model property changed. For example:
Current url: my/controller/someaction?name=Alex&age=20&from=fr&CurrentA=
with model ?name=Alex&age=20&from=fr&CurrentA=
If user clicks on <a> with text foo it should be redirected on my/controller/someaction?name=Alex&age=20&from=fr&CurrentA=foo
then is clicks on <a> with text bar and it should be now redirected on my/controller/someaction?name=Alex&age=20&from=fr&CurrentA=bar
So entire query string (except one parameter) should be preserved to send current model state to server while I want to set one value and redirect it to the same page but with new value.
Eventually, it should acts like postback with one extra value setted to model
Is it possible or I should use JS and perform everything myself?
Manually i solved it like this:
First, create hidden fields for every property in model:
<form asp-controller="search" asp-action="index" method="get" role="form" id="searchForm" asp-antiforgery="false">
<input asp-for="SessionId" type="hidden" name="sessionId" value="#Model.SessionId" />
<input asp-for="Quantity" type="hidden" name="quantity" value="#Model.Quantity"/>
<input asp-for="SortField" type="hidden" name="sortField" value="#Model.SortField"/>
<input asp-for="IsAscending" type="hidden" name="IsAscending" value="#Model.IsAscending" />
<input asp-for="Offset" type="hidden" name="offset" value="0" />
...
</form>
Then, use JS to replace value in hidden field and then submit form. Values from inputs will be autimatically converter in query string, so everything works fine:
function sortDocuments(sortField) {
var sField = document.getElementById('SortField');
var isDescending = document.getElementById('IsAscending');
if (sField.value === sortField) {
if (isDescending.value.toUpperCase() === 'FALSE') {
isDescending.value = 'TRUE';
} else {
sField.value = 'rank';
isDescending.value = 'FALSE';
}
} else {
sField.value = sortField;
isDescending.value = 'FALSE';
}
document.getElementById('searchForm').submit();
}
Not very elegant, but it does its job.

MVC 6 .Net Core1 Create Custom tag helper for Likert Scale

I am trying to create a tag helper for MVC 6 using .Net Core RC1. I have found a few good sources but not something super close, this was the closest I found and took elements I thought I needed to create my existing code:
To start with this is my target HTML:
<span class="form-control">
Highly Disagree
<input type="radio" name="MakingSense" value=1 />
<input type="radio" name="MakingSense" value=2 />
<input type="radio" name="MakingSense" value=3 />
<input type="radio" name="MakingSense" value=4 />
<input type="radio" name="MakingSense" value=5 />
Highly Agree
</span>
Right now I am just trying to get one of the input tags to show. If I can figure that out I will add a loop to get the others. Here is my TagHelper
[HtmlTargetElement("input", Attributes = LikertForAttributeName)]
public class LikertTagHelper : TagHelper
{
private const string LikertForAttributeName = "likert-for";
[HtmlAttributeName(LikertForAttributeName)]
public string ModelField { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
var content = new StringBuilder();
var input = new TagBuilder("input");
input.MergeAttribute("type", "radio");
input.MergeAttribute("name", ModelField);
input.MergeAttribute("value", "1");
content.AppendLine(input.ToString());
output.Content.SetContent(content.ToString());
output.PreContent.SetHtmlContent("<span class=\"form-control\"");
output.PostContent.SetHtmlContent("</span>");
}
}
Here is my razor cshtml:
<input likert-for="CharacterUnderstanding" />
However, I only get this as my html output:
<input />
So it is picking up the tag and processing it but not as I expect. Help in where I went wrong will be much appreciated.
Your tag helper starting point is an input tag, so content starts being a self closing input tag.
The first thing you want to do is turn that into a span tag, for example:
//Replace initial output (an input tag) with a span
var outerTag = new TagBuilder("span");
outerTag.AddCssClass("form-control");
output.MergeAttributes(outerTag);
output.TagName = outerTag.TagName;
output.TagMode = TagMode.StartTagAndEndTag;
Now since output is a span tag you can start adding the inner contents:
The Highly Agree, Highly Disagree labels can be added as pre/post content (still inside the span):
//Add Pre/Post texts
output.PreContent.SetHtmlContent("Highly Disagree");
output.PostContent.SetHtmlContent("Highly Agree");
The radio buttons can be appended to the content of the span:
//Add the radio buttons
for(var x =0; x<5; x++)
{
var input = new TagBuilder("input");
input.MergeAttribute("type", "radio");
input.MergeAttribute("name", ModelField);
input.MergeAttribute("value", x.ToString());
output.Content.Append(input);
}
With this tag helper in place, the following line in the razor view:
<input likert-for="CharacterUnderstanding" />
Is rendered as:
<span class="form-control">
Highly Disagree
<input name="CharacterUnderstanding" type="radio" value="0">
<input name="CharacterUnderstanding" type="radio" value="1">
<input name="CharacterUnderstanding" type="radio" value="2">
<input name="CharacterUnderstanding" type="radio" value="3">
<input name="CharacterUnderstanding" type="radio" value="4">
Highly Agree
</span>
As a side note, you want to be careful when adding contents using the overloads that accept strings. In your original code the line content.AppendLine(input.ToString()); was actually appending Microsoft.AspNet.Mvc.Rendering.TagBuilder instead of the tag builder content.

keeping the data in a form after it has been sent

I have a form that you enter data into and it performs a calculation on it and give an answer. what i want to do is for it to keep the data in the form so that you can quickly repost so that you don't have to change all the data. but I cant keep coming up with the error of it not existing, which I suppose is correct until the form has been posted!
#{
var total = 0m;
var totalMessage = "";
if (IsPost)
{
var age = Request["frmage"].AsInt(0);
var weight = Request["frmweight"].AsDecimal();
var SerCre = Request["frmSerCre"].AsDecimal();
var sexfactor = Request["frmGender"]== "M" ? 1.23m : 1.04m;
total =Convert.ToDecimal ((((140 - age)*weight)* sexfactor )/SerCre ) ;
totalMessage = total.ToString("0.00") + "(ml/min) ";
}
}
<div class="memberRegistration">
<form method="post">
<p>
<label class="formLabel">Age:</label> in years
<input class="formTextField" type="text" name="frmAge" size="3" value="#age"/>
</p>
<p>
<label class="formLabel">Weight:</label> in Kg (1st = 6.35kg)
<input class="formTextField" type="text" name="frmWeight" value="#weight"/>
</p>
<p>
<label class="formLabel">Serum Creatinine:</label> in μmol/L
<input class="formTextField" type="text" name="frmSerCre" value="#SerCre"/>
</p>
<p>
<label class="fieldLabel">Gender:</label>
<select name="frmGender" id="select" value="#sexfactor">
<option value="M">Male</option>
<option value="F">Female</option>
</select>
</p>
<p><input type="submit" value="Calculate" /></p>
</form>
<p>Calculated creatinine clearance <b>#totalMessage</b></p>
</div>
Try this
var age = 0;
if (IsPost)
{
age = Request["frmage"].AsInt(0);
}
<input class="formTextField" type="text" name="frmAge" size="3" value="#age"/>
But normally it would be better to use a model to hold your values, then in your controller you pass those values back again to your form
Enable the ViewState of the page and controls and also use aspx control, not HTML.
I don't thing that i realy understand the Question because the default thing is that the web page keeps it's view state so the data will still be the same after the post back but here's the solution :
you can simply use ASP Controls because it keep it's view state
or you can give each control of them it's value in the C# , you can assign to each control it's value back
Hope I Helped
Since you are using ASP.NET MVC Razor, what you can do is, do not submit the form using <input type="submit" value="Calculate" /> , instead change it to a simple button like
<input type="button" value="Calculate" onclick="javascript:Submitform();" />
and submit the form using Jquery POST.e.g. like below
function SubmitForm(){
var formData = $("form").serialize() ;
var submitUrl = 'yourURL' ;
$.ajax({
type : 'POST' ,
url : submitUrl ,
data : formData ,
success : function (data ){ alert ("Request successful") ;}
error : function (jqXHR, status , errorthrown) { alert ("error Occured");}
});
}

How do you the change Input Hidden Value?

I want to change the value of the input tag. But it's not working at all. I already found a working code that would change the value of the Select tag, but I haven't found a code that works well to change the value of the input tag below.
<div id="phmiddle_0_CheckoutShippingInfo1_selectAddressDiv" name="selectAddressDiv">
<select class="selecta" name="selAddressBook" id="selAddressBook">
<option value="-1">Create a new address</option>
<option value="{adbd6ae0-abf8-40ea-a18a-998afaeb37ad}">AAA AAA</option>
<option value="{0e0e26a0-c490-476f-9a00-d3d76d7d69cd}">BBB BBB</option>
<option value="{84496563-8dcb-42e6-b728-60646faf81d0}">CCC CCC</option>
</select>
<input type="hidden" name="idOfShiptoDefaultedToOrSelected"
id="idOfShiptoDefaultedToOrSelected"
value='{adbd6ae0-abf8-40ea-a18a-998afaeb37ad}' />
</div>
This is the code I used to try to change the hidden input value.
private void button9_Click(object sender, EventArgs e)
{ webBrowser1.Document.GetElementById("idOfShiptoDefaultedToOrSelected").SetAttribute("value", "-1");
}
It wouldn't work at all. Am I missing something here like a select or click? I already tried them.
I also tried this one too
webBrowser1.Document.GetElementById("selAddressBook").SetAttribute("value", "-1");
^ THAT code can change the seladdressbook but it wouldn't change the input hidden value, which is idOfShiptoDefaultedToOrSelected.
Why not do it in JavaScript:
$("#BUTTON_ID").click(function() {
$("idOfShiptoDefaultedToOrSelected").val("NEW_VALUE");
});

Categories

Resources