how to get the selected value from a drop down list and transfer it to a viewbag - asp.net

View
...Some Codes...
<select class="form-control" style = "width:400px">
<option selected> select issue type </option>
#foreach( var item in Model._issueList)
{
<option>#item.issueName</option>
}
</select>
...Some Codes...
Output of my dropdown
dropDown: issue_one, issue_two, issue_three
Now I want to choose my issue_three in my drop down and save it in a Viewbag.select, want should be the proper code so that I can transfer the issue_three to my Viewbag.select
TEST
...foreach code...
Viewbag.select = ????

View
<select class="form-control" style = "width:400px">
<option selected> Select Company Name </option>
#foreach (var item in Model._issueList)
{
<option id="issueSelect" onclick="transferIssue('#item.issueNo')">#item.issueName</option>
}
</select>
#Html.HiddenFor( m => m.variable,new { #class = "form-control", style = "width:400px", #id = "issue" })
...Some codes...
<button type ="submit" id='submit_button'>Submit</button>
SCRIPT Use JQUERY
function transferIssue(x){ $('#issue')val(); }
jQuery(document).on('click', '#submit_button', function (ev) {
ev.preventDefault();
var _issue = jQuery('#issue').val();
var _url = '#Url.Action("Jobs")' + '?value='+ _issue;
window.location.href = _url;
});

Related

ASPX Select dropdown with Button Linking to another page

I am unfamiliar with select dropdowns and links. If I have:
<select>
<option value="">Select</option>
<option value="/Applications.aspx">Applications</option>
<option value="/EditApplications.aspx">Edit Application</option>
<option value="/AddApplications.aspx">Add Applications</option>
</select>
<button>Go</button>
When the user selects their option, how do I link the button to when the user clicks the button, it goes to the selected page within the dropdown in ASPX? I am sure I need to bind it somehow to the codebehind but I am not sure how to do this.
A very basic solution would be something like the snippet below. On the button click read the value of the select and redirect to that url. Don't forget to add an id to the select. And you need to add type="button" to the button, otherwise it will trigger a form post.
<select id="MySelect">
<option value="">Select</option>
<option value="/Applications.aspx">Applications</option>
<option value="/EditApplications.aspx">Edit Application</option>
<option value="/AddApplications.aspx">Add Applications</option>
</select>
<button type="button" onclick="GoTOUrl()">Go</button>
<script>
function GoTOUrl() {
var url = $('#MySelect').val();
if (url === '')
return;
location.href = url;
}
</script>
No need to wire it up to the code behind. This can all be handled client side with some javascript.
Make the button an actual link. Then update the href attribute and optionally the text.
//Get relevent elements
var linkDropDown = document.getElementById("MySelect");
var link = document.getElementById("Link");
//Wire up event listener to the dropdown
linkDropDown.addEventListener("change", function() {
var defaultVal = this.options[0].value;
//Toggle the inactive class based on selected value
link.classList.toggle("inactive", this.value === defaultVal);
//Set Href
link.href = this.value;
//Set Text using ternary operation
link.text = this.value === defaultVal ? "Go.." : "Go to " + this.options[this.selectedIndex].text;
});
.inactive {
pointer-events: none;
color: grey;
}
<select id="MySelect">
<option value="/">Select</option>
<option value="/Applications.aspx">Applications</option>
<option value="/EditApplications.aspx">Edit Application</option>
<option value="/AddApplications.aspx">Add Applications</option>
</select>
Go..
It is also possible to encapsulate this to automagically work if you have more than set of this on the page.
//Get relevent elements
var dropdowns = document.querySelectorAll(".dropdownSelect");
//Wire up event listeners
for(var i = 0; i < dropdowns.length; i++){
dropdowns[i].addEventListener("change", function(event){
if(event.target.nodeName === "SELECT") {
let sel = event.target;
let link = this.querySelector(".dropdownLink");
let defaultVal = sel.options[0].value;
//Toggle the inactive class based on selected value
link.classList.toggle("inactive", sel.value === defaultVal);
//Set HREF
link.href = sel.value;
//Set Text using ternary operation
link.text = sel.value === defaultVal ? "Go.." : "Go to " + sel.options[sel.selectedIndex].text;
}
})
}
.inactive {
pointer-events: none;
color: grey;
}
<div class="dropdownSelect">
<select>
<option value="/">Select</option>
<option value="/Applications.aspx">Applications</option>
<option value="/EditApplications.aspx">Edit Application</option>
<option value="/AddApplications.aspx">Add Applications</option>
</select>
Go..
</div>
<div class="dropdownSelect">
<select>
<option value="/">Select</option>
<option value="/WebSites.aspx">Web Sites</option>
<option value="/EditWebSites.aspx">Edit Web Sites</option>
<option value="/AddWebSites.aspx">Add Websites</option>
</select>
Go..
</div>

Use drop down result to filter another dropdown C# MVC

I am trying to update a drop down based on the users selection in the first drop down. I found this SO post on the topic, but Im not quite sure how to add the jquery to filter values to my Razor view. Can someone point me in the right direction?
My view so far:
#using System.Security.Claims;
#model UpdateClaimFormModel;
<h2>UpdateClaimView</h2>
#using (#Html.BeginForm())
{
<select name="emailcheese">
<option selected disabled>Select User</option>
#foreach (var i in Model.UserNames)
{
<option>#i.ToString()</option>
}
</select>
<select name="authpolicy">
<option selected disabled>Select Claim:</option>
#foreach (var i in Model.UserClaims)
{
<option>#i.Type.ToString()</option>
}
</select>
<div class="form-group">
<button type="submit" class="btn btn-default">Whoo</button>
</div>
}
My Goal:
Select User [bob, bill, jim]
Select Claim: If user bob:[1,2,3], If user bill:[1,4,8], If user him:[4,5,6]
so simpley you can do something like this
#using (#Html.BeginForm())
{
<select name="emailcheese" id="selectUserNames">
<option selected disabled>Select User</option>
#foreach (var i in Model.UserNames)
{
<option>#i.ToString()</option>
}
</select>
<select name="authpolicy" id="selectAuthPolicy">
</select>
<div class="form-group">
<button type="submit" class="btn btn-default">Whoo</button>
</div>
}
now in the script part
$(function(){
var userClaims = #Html.Raw(Json.Encode(Model.UserClaims));
$(document).on('change','#selectUserNames'function(){
var selectedVal = $(this).val();
if(selectedVal == 'bob')
{
var html ='<option selected disabled>Select Claim:</option>';
for(var i=1;i<userClaims.length;++i)
{
if(i==1||i==2||i==3)
{
html=html+'<option>'+userClaims[i].Type+'</option>';
}
}
$('#selectAuthPolicy').html(html);
}
})
})
this is just a basic dea of how you can achieve this i just tried for bob there are many other ways to immplement ths

cascading dropdown angularjs mvc

i am getting null values
$scope.GetDepartment = function (Department) {
$http.get('/Official/GetDepartment?Department=' + Department).then(function (data) {
console.log(data);
$scope.department= data.data;
});
};
Html
<select ng-model="empModel.division" id="" name="Division" class="form-control"
ng-click = "GetDepartment(empModel.division)"
ng-change = "GetDepartment(empModel.division)"
ng-options="c.division as c.division for c in division" >
<option selected="selected">Select</option>
</select>
<select ng-model="empModel.department" id="" name="Department" class="form-control"
ng-options="d.department as d.department for d in department">
<option></option>
</select>
When i select divison i am not getting anything in department dropdown
Controller
public JsonResult GetDepartment(string Department)
{
var department = db.Depts.Where(x => x.Department == Department).
GroupBy(x => x.Department).
Select(x => x.FirstOrDefault()).
OrderBy(x => x.Department).ToList();
return Json(department);
}
Your angular part for retrieve division data
function GetDesignation(input) {
$http.get('/Official/GetDesignation?designation='+input).then(function (data) {
console.log(data);
$scope.designation = data.data;
});
};
change in HTML using ng-change directive there
<select ng-model="empModel.division" id="" name="Division" class="form-control" ng-change = "GetDesignation(empModel.division)"
ng-options="c.division as c.division for c in division" >
<option></option>
</select>
New HTML tag for load Designation data in dropdown
<select ng-model="empModel.designation" id="" name="Designation" class="form-control"
ng-options="c.designation as c.designation for c in designation" >
<option></option>
</select>

How to put just distinct values into select control MVC ASP.NET?

This is my index view. I tried with ViewBag but it doesn't work, maybe because I want to get values from foreign key. I am new to ASP.NET.
<form id="forma" action="/InspekcijskeKontrole/VratiKontrole" method="get">
<div class="form-group">
<label for="Select1">Odaberite inspekcijsko tijelo:</label>
<select name="Select1" id="Select1" class="form-control" onchange="sacuvaj()">
<option value="-1">Selektujte inspekcijsko tijelo:</option>
#foreach (var i in ViewBag.Select1) {
<option value="#i.Value">#i.Text</option>
}
</select><br />
<label for="Select2">Odaberite vremenski period kontrole:</label>
<select name="Select2" id="Select2" class="form-control" onchange="sacuvaj1()">
<option value="-1">Selektujte vremenski period kontrole:</option>
#foreach(var i in Model)
{
<option value="#i.DatumInspekcijskeKontrole.ToString("dd.MM.yyyy")">#i.DatumInspekcijskeKontrole.ToString("dd.MM.yyyy")</option>
}
</select>
</div>
This is my controller
public ActionResult VratiKontrole(int Select1, string Select2)
{
IEnumerable<string> tijelaNaziv = db.InspekcijskaKontrolas.OrderBy(i => i.InspekcijskoTijelo.NazivInspekcijskogTijela).Select(i => i.InspekcijskoTijelo.NazivInspekcijskogTijela).Distinct();
ViewBag.Select1 = new SelectList(tijelaNaziv);
IQueryable<InspekcijskaKontrola> listaKontrola = db.InspekcijskaKontrolas.Select(i => i);
if (!string.IsNullOrEmpty(Select1.ToString())&&!string.IsNullOrEmpty(Select2.ToString()))
{
string[] parts = Select2.Split('.');
DateTime datum = new DateTime(int.Parse(parts[2]), int.Parse(parts[1]), int.Parse(parts[0]));
listaKontrola = listaKontrola.Where(l => l.InspekcijskoTijeloId == Select1).Where(l => l.DatumInspekcijskeKontrole == datum).Select(l => l);
}
return View(listaKontrola.ToList());
}
(Posted on behalf of the OP).
This is solved. I just put into view:
#foreach (var i in Model.Select(i=>i.InspekcijskoTijelo).Distinct()) {
<option value="#i.InspekcijskoTijeloId">#i.NazivInspekcijskogTijela</option>
}

how to give #readonly in DropdownListfor in asp.net MVC 4? [duplicate]

What option do I need to set to make a drop down box readonly when using MVCs Html.DropDownList?
I've tried things like....
Html.DropDownList("Types", Model.Types, new { _Enabled = "false" })
...and many different things along this line; alas no joy!
I thought this would be an easy.....and it probably is!
Try this
Html.DropDownList("Types", Model.Types, new { #disabled = "disabled" })
Regarding the catch 22:
If we use #disabled, the field is not sent to the action (Mamoud)
And if we use #readonly, the drop down bug still lets you change the value
Workaround: use #disabled, and add the field hidden after the drop down:
#Html.HiddenFor(model => model.xxxxxxxx)
Then it is truly disabled, and sent to the to the action too.
<script type="text/javascript">
$(function () {
$(document) .ajaxStart(function () {
$("#dropdownID").attr("disabled", "disabled");
})
.ajaxStop(function () {
$("#dropdownID").removeAttr("disabled");
});
});
</script>
I had to disable the dropdownlist and hide the primary ID
<div class="form-group">
#Html.LabelFor(model => model.OBJ_ID, "Objs", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("OBJ_ID", null, htmlAttributes: new { #class = "form-control", #disabled = "disabled"})
#Html.HiddenFor(m => m.OBJ_ID)
#Html.ValidationMessageFor(model => model.OBJ_ID, "", new { #class = "text-danger" })
</div>
</div>
A tip that may be obvious to some but not others..
If you're using the HTML Helper based on DropDownListFor then your ID will be duplicated in the HiddenFor input. Therefore, you'll have duplicate IDs which is invalid in HTML and if you're using javascript to populate the HiddenFor and DropDownList then you'll have a problem.
The solution is to manually set the ID property in the htmlattributes array...
#Html.HiddenFor(model => model.Entity)
#Html.EnumDropDownListFor(
model => model.Entity,
new {
#class = "form-control sharp",
onchange = "",
id =` "EntityDD",
disabled = "disabled"
}
)
Or you can try something like this:
Html.DropDownList("Types", Model.Types, new { #readonly = "true" })
Put this in style
select[readonly] option, select[readonly] optgroup {
display: none;
}
I just do this and call it a day
Model.Id > -1 ? Html.EnumDropDownListFor(m => m.Property, new { disabled = "disabled" }) : Html.EnumDropDownListFor(m => m.Property)
#Html.DropDownList("Types", Model.Types, new { #disabled = "" })
Works
Html.DropDownList("Types", Model.Types, new { #disabled = "disabled" })
#Html.Hidden(Model.Types)
and for save and recover the data, use a hidden control
For completeness here is the HTML Helper for DropDownListFor that adds enabled parameter, when false select is disabled. It keeps html attributes defined in markup, or it enables usage of html attributes in markup, it posts select value to server and usage is very clean and simple.
Here is the code for helper:
public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes, bool enabled)
{
if (enabled)
{
return SelectExtensions.DropDownListFor<TModel, TProperty>(html, expression, selectList, htmlAttributes);
}
var htmlAttributesAsDict = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
htmlAttributesAsDict.Add("disabled", "disabled");
string selectClientId = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
htmlAttributesAsDict.Add("id", selectClientId + "_disabled");
var hiddenFieldMarkup = html.HiddenFor<TModel, TProperty>(expression);
var selectMarkup = SelectExtensions.DropDownListFor<TModel, TProperty>(html, expression, selectList, htmlAttributesAsDict);
return MvcHtmlString.Create(selectMarkup.ToString() + Environment.NewLine + hiddenFieldMarkup.ToString());
}
and usage, goal is to disable select if there is just one item in options, markup:
#Html.DropDownListFor(m => m.SomeValue, Model.SomeList, new { #class = "some-class" }, Model.SomeList > 1)
And there is one even more elegant HTML Helper example, no post support for now (pretty straight forward job, just use HAP and add hidden input as root element sibling and swap id's):
public static MvcHtmlString Disable(this MvcHtmlString previous, bool disabled, bool disableChildren = false)
{
if (disabled)
{
var canBeDisabled = new HashSet<string> { "button", "command", "fieldset", "input", "keygen", "optgroup", "option", "select", "textarea" };
var doc = new HtmlDocument();
doc.LoadHtml(previous.ToString());
var rootElements = doc.DocumentNode.Descendants().Where(
hn => hn.NodeType == HtmlNodeType.Element &&
canBeDisabled.Contains(hn.Name.ToLower()) &&
(disableChildren || hn.ParentNode.NodeType == HtmlNodeType.Document));
foreach (var element in rootElements)
{
element.SetAttributeValue("disabled", "");
}
string html = doc.DocumentNode.OuterHtml;
return MvcHtmlString.Create(html);
}
return previous;
}
For example there is a model property bool AllInputsDisabled, when true all html inputs should be disabled:
#Html.TextBoxFor(m => m.Address, new { placeholder = "Enter address" }).Disable(Model.AllInputsDisabled)
#Html.DropDownListFor(m => m.DoYou, Model.YesNoList).Disable(Model.AllInputsDisabled)
You could use this approach
Disabling all the options except the selected one:
<select>
<option disabled>1</option>
<option disabled>2</option>
<option selected>3</option>
</select>
This way the dropdown still submits, but the user can not select another value.
With jQuery
<script>
$(document).ready(function () {
$('#yourSelectId option:not(:selected)').prop("disabled", true);
});
</script>
try with #disabled and jquery, in that way you can get the value on the Controller.
Html.DropDownList("Types", Model.Types, new {#class = "your_class disabled", #disabled= "disabled" })
Add a class called "disabled" so you can enabled by searching that class(in case of multiples disabled fields), then you can use a "setTimeout" in case of not entering controller by validation attributes
<script>
function clickSubmit() {
$("select.disabled").attr("disabled", false);
setTimeout(function () {
$("select.disabled").attr("disabled", true);
}, 500);
}
</script>
submit button like this.
<button type="submit" value="Submit" onclick="clickSubmit();">Save</button>
in case of inputs, just use #readonly="readonly"
#Html.TextBoxFor("Types",Model.Types, new { #class = "form-control", #readonly= "readonly" })
You can set the select as readonly and then run some jquery to disable the options except the selected value. You cant change the value and it's included when the form is submitted.
$(document).ready(function () {
$('select option').removeAttr('disabled');
$('#readonlyTest').find('select[readonly] option').not('select[readonly] option[selected]').attr('disabled', 'disabled');
});
$('#submitButton').click(function(e) {
var formData = $('form').serialize();
$('#formData').html(formData);
});
body {
margin: 50px;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="form-group">
<label for="scopeReadonlyNoJs">Scope Readonly No Js</label>
<select class="form-control" id="scopeReadonlyNoJs" name="scopeReadonlyNoJs" readonly="readonly">
<option value="">Select..</option>
<option selected="selected" value="readonlyNoJsScopeValue1">Scope Value 1</option>
<option value="readonlyNoJsScopeValue2">Scope Value 2</option>
</select>
<small id="scopeReadonlyNoJsHelp" class="form-text text-muted">This is read only and no js is applied. It looks disabled but you can change the values.</small>
</div>
<div id="readonlyTest" class="form-group">
<label for="scopeReadonly">Scope Readonly</label>
<select class="form-control" id="scopeReadonly" name="scopeReadonly" readonly="readonly">
<option value="">Select..</option>
<option selected="selected" value="readonlyScopeValue1">Scope Value 1</option>
<option value="readonlyScopeValue2">Scope Value 2</option>
</select>
<small id="scopeReadonlyHelp" class="form-text text-muted">This is read only and is disabled via js by disabling the options except the selected one.</small>
</div>
<div class="form-group">
<label for="scopeDisabled">Scope Disabled</label>
<select class="form-control" id="scopeDisabled" name="scopeDisabled" disabled="disabled">
<option value="">Select..</option>
<option selected="selected" value="disabledScopeValue1">Scope Value 1</option>
<option value="disabledScopeValue2">Scope Value 2</option>
</select>
<small id="scopeDisabledHelp" class="form-text text-muted">This is disabled and wont be posted.</small>
</div>
<button id="submitButton" type="button">
Submit
</button>
</form>
<p id="formData">
</p>
I've create this answer after referring above all comments & answers.
This will resolve the dropdown population error even it get disabled.
Step 01
Html.DropDownList("Types", Model.Types, new {#readonly="readonly"})
Step 02
This is css pointerevent remove code.
<style type="text/css">
#Types {
pointer-events:none;
}
</style>
Then you can have expected results
Tested & Proven

Resources