Dropdown lists selected item to Html button hyper links value - c#

I have a dropdownlist and the Html hyperlink button.So i need when i select something in the dropdown list and then i click the button then Hyperlinks Quantity property fills with Dropdown list selected item value.
<div class="form-group col-6 mt-0 mt-lg-3 d-flex align-items-end">
<select id="drpQuantity">
<option value="0">--Select --</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<a href="#Url.Action("AddNewItems", "Home",
new { ItemId = QitemId,
Quantity = //I need dropdown lists selected value here})">
<input type="submit" class="btn btn-primary btn-block rounded-pill" id="#QitemId" value="Add to Cart" />
</a>
</div>

As #Jasen said before, #Url.Action() helper's routeValues parameters are rendered server-side before sending to browser and you can't change it directly with selected value from <select> element. You could use client-side code which provides additional query string parameter using selected value from <select> element, as provided in this example:
Hyperlink example
<a id="link" href="#">Add New</a>
Client-side manipulation
$('#drpQuantity').change(function () {
var selected = $(this).val();
// use prop function to set href attribute of target anchor link
$('#link').prop('href', '#Url.Action("AddNewItems", "Home", new { ItemId = QitemId })' + '&Quantity=' + selected);
});
If you want to use plain/vanilla JS, you need to handle onchange event from <select> and set href attribute after getting anchor link ID/tag name:
<select id="drpQuantity" onchange="setUrl(this)">...</select>
<script>
function setUrl(element) {
var value = element.value;
document.getElementById('link').href = '#Url.Action("AddNewItems", "Home", new { ItemId = QitemId })' + '&Quantity=' + selected;
}
</script>
The anchor link should be rendered like this example:
<a id="link" href="/Home/AddNewItems?ItemId=1&Quantity=1">Add New</a>
Live example: .NET Fiddle

Related

How to set a URL parameter and set the value of a select option on page load based on the URL parameter

I have a select dropdown that is populated based on a database table. I want to use a query string parameter in the url that automatically selects an option in the dropdown.
<div class="col-xl-7">
<select name="autoMessageTemplates" id="autoMessageTemplates" class="form-select" #onchange="FindMessageTemplateAndSendToParent">
<option></option>
#foreach (var template in messageTemplates ?? Enumerable.Empty<MessageTemplateDto>())
{
<option>#template.TemplateKey</option>
}
</select>
</div>
I'm new to using url parameters and all of the examples I have found are in jquery or in php. So how would I use a url parameter to have a dropdown option selected based on it in blazor?
Edit:
I have tried to find a solution and have come up with the below but it doesn't work. Can some suggest an edit to kae it work or a different solution entirely is welcome.
<div class="col-xl-7">
<select name="autoMessageTemplates" id="autoMessageTemplates" class="form-select" #onchange="FindMessageTemplateAndSendToParent">
<option></option>
#foreach (var template in messageTemplates ?? Enumerable.Empty<MessageTemplateDto>())
{
<option selected="#(template.Id == messageTemplateId) ? selected : ''">#template.TemplateKey</option>
}
</select>
</div>

Display the selected element from a dropdown combobox in C# ASP.NET MVC

I have a dropdown combobox and a submit button in my application.
What I want to achieve is: every time the submit button is pressed, I want the item that was selected in the dropdown menu to be displayed on the page.
Here is a screenshot with the combobox and the submit button
The combobox gets the data from a database here is the code for binding if you need it :
<select name="select_box" class="selectpicker" id="select_box" data-live-search-style="begins" data-live-search="true">
<option value="">Select Meal</option>
#foreach(var obj in Model)
{
<option value="">#obj.Name</option>
}
</select>
From what I've found after researching this problem , I found out that in Javascript there is a method : getElementById(id) which returns the element (in my case the combobox).
I wonder if there is something similar for C# or if there is an alternative?
Edit :
Here is an example of the thing that I'm trying to accomplish, with some differences : instead of a combobox the input is taken from a text field.
<!DOCTYPE html>
<html>
<head>
<script>
function testVariable() {
var strText = document.getElementById("textone").value;
var strText1 = document.getElementById("textTWO").value;
var result = strText + ' ' + strText1;
document.getElementById('spanResult').textContent = result;
}
</script>
</head>
<body>
<input type="text" id="textone" />
<input type="text" id="textTWO" />
<button onclick="testVariable()">Submit</button> <br />
<span id="spanResult">
</span>
</body>
</html>
No you can't do with C# in .NET Core MVC.
you can do it only with javascript.
but if you use .Net Core Blazor, you can do like this.
<p>
<label>
Select one or more cars:
<select #onchange="SelectedCarsChanged" multiple>
<option value="audi">Audi</option>
<option value="jeep">Jeep</option>
<option value="opel">Opel</option>
<option value="saab">Saab</option>
<option value="volvo">Volvo</option>
</select>
</label>
</p>
<p>
Selected Cars: #string.Join(", ", SelectedCars)
</p>
#code {
public string[] SelectedCars { get; set; } = new string[] { };
void SelectedCarsChanged(ChangeEventArgs e)
{
if (e.Value is not null)
{
SelectedCars = (string[])e.Value;
}
}
}
https://learn.microsoft.com/en-us/aspnet/core/blazor/components/data-binding?view=aspnetcore-6.0#multiple-option-selection-with-select-elements

How to access the data attribute from a dropdownlists' selected item using c# razor syntax

How would I go about storing a selected items "data" attribute value into a variable using c# razor syntax? I only have a view to work with and there as no models or controllers.
var brokerID = Request["brokerSelect"];
<select class="form-control" id="brokerSelect" name="brokerSelect" title="Please Select a broker" required>
<option value="">- Select Broker -</option>
#foreach (var row in brokers)
{
<option data="#row.ClaimType" value="#row.ID" #(brokerID == row.ID.ToString() ? "selected" : "")>#row.Name</option>
}
</select>
The Request["brokerSelect"] will return the value of the selected item, but i need the "data" attribute value. I did look down the javascript route, but do not think this is possible as i need to do more with this value.
Is there anyway to do this?
Data attribute values are not accessible to server-side code. You will need to use JavaScript to access the value. You can assign the value to a hidden field in the form, which will ensure that it is posted to the server, so long as the hidden input has a name attribute:
<input type="hidden" name="claimtype" />
<select class="form-control" id="brokerSelect" name="brokerSelect" title="Please Select a broker" required>
<option value="">- Select Broker -</option>
#foreach (var row in brokers)
{
<option data-claimtype="#row.ClaimType" value="#row.ID" #(brokerID == row.ID.ToString() ? "selected" : "")>#row.Name</option>
}
</select>
<script>
document.getElementById("brokerSelect").addEventListener('change', function(e){
document.querySelector('[name="claimtype"]').value = e.target.options[e.target.selectedIndex].dataset.claimtype;
});
</script>
By the way, if you are using Razor Pages and not the older ASP.NET Web Pages, you shouldn't be using Request["foo"] to access posted values. You should be using ModelBinding: https://www.learnrazorpages.com/razor-pages/model-binding

How can i set selected item property from the list using code behind?

<div id="Div1" class="myTeams">
<div class="listTitle">My Teams</div>
<div id="myTeams">
<select id="myGroupList" name="myGroupList" onchange="reloadMYUser('myIntContacts');" size="10" />
<option value="abc_group" selected >abc</option>
<option value="def_group" >def</option>
<option value="ghi_group" >ghi</option>
<option value="jkl_group" >jki</option>
</select>
</div>
</div>
i would like to search any group from the above list if it finds my group it should apply selected property for that list item. how can i do this from the codebehind?
Are you using ASP.net? if so you can use asp control... DropDownList (instead of simple select)
If you can't, try something like this:
add runat="server" to myGroupList on .aspx file.
then on .cs file:
for (int i = 0; i < myGroupList.Items.Count; i++)
{
if (element.Children[i].InnerText == "abc_group")
{
element.SetAttribute("selected", "selected");
break;
}
}

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");}
});
}

Categories

Resources