Pass html.dropdownlistfor current value to Actionlink? - javascript

is it possible to pass #Html.DropDownListFor current value to action link? I want to pass the template value to the Sample controller with Create Action. Below code not work because #Model.SurveyTemplate does not return any value. Is it need JavaScript to retrieve? Please guide me.
Drop Down List:
#Html.LabelFor(model => model.Survey_Template, "Survey Template")
#Html.DropDownListFor(model => model.Survey_Template, new SelectList(
new List<Object>{
new { value = "Style1" , text = "Style1" },
new { value = "Style2" , text = "Style2" },
new { value = "Style3" , text = "Style3"}
},
"value",
"text",
0))
ActionLink:
#Html.ActionLink("_", "Create", "Sample",
new { template = #Model.Survey_Template },
new { #id = "popup-link", #class = "classname2" })

You have to do this with JavaScript, the razor syntax is recognized only on server side. This means that #Model.Survey_Template will be rendered when user request the page and will have the default value.
If you choose to do it with JavaScript remember that you need to save the base url and to append parameters to it based on what has been selected.
This steps will help you to achieve your desired result:
Attach a change event on your dropdown.
Get the selected value and construct the new url
Replace the url (href) of the action (<a .. />)
Note: I didn't write the code because I want you to surpass yourself.
I think what you try to achive it's a form with GET.
#using(Html.BeginForm("Create", "Sample", FormMethod.GET)){
#Html.LabelFor(model => model.Survey_Template, "Survey Template")
#Html.DropDownListFor(model => model.Survey_Template, new SelectList(
new List<Object>{
new { value = "Style1" , text = "Style1" },
new { value = "Style2" , text = "Style2" },
new { value = "Style3" , text = "Style3"}
},
"value",
"text",
0))
<input type="submit" value="_" class="classname2" id="popup-link" />
}

Related

How can I populate the same value on the below dropdownlist

enter image description here
enter image description here
I have here 2 viewbag in my controller
ViewBag.MyCategory = new SelectList(db.RecyclableType, "id", "type");
ViewBag.iddd = new SelectList(db.RecyclableType, "id", "type");
and a View
#Html.DropDownList("iddd", (IEnumerable<SelectListItem>)ViewBag.iddd, "SELECT ITEM TYPE", new { #class = "form-control" })
#Html.DropDownList("MyCategory", (IEnumerable<SelectListItem>)ViewBag.MyCategory, "SELECT ITEM TYPE", new { #class = "form-control"})
i tried to create a function like below but nothing is working
document.getElementById("iddd") = document.getElementById("MyCategory");
You can do it using jQuery
First on change of iddd dropdown get its value
Set the value to MyCategory dropdown and set the attribute to
selected
$("#iddd").change(function () {
var value = $("#iddd").val();
$("#MyCategory").val(value).attr("selected", "selected");
});
Note: Add jQuery script file in head section
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Replace text in values from dropdowns in razor statements

I have a HTML form with some dropdowns. I need the values of the selected item in the dropdowns to replace tags from another dropdown.
#Html.DropDownListFor(model => model.TrainID, new SelectList(Model.TrainItems, "Value", "Text"), htmlAttributes: new { id = "train" })
#Html.DropDownListFor(model => model.ReasonID, new SelectList(Model.ReasonItems, "Value", "Text"), htmlAttributes: new { id = "reason" })
#Html.DropDownListFor(model => model.MessageID, new SelectList(Model.MessageItems, "Value", "Text"), htmlAttributes: new { id = "message" })
I need the values of the train and the reason selected by the user to replace certain parts of the message item selected.
For example, the message selected would say: "Train # [NUM] has been cancelled due to [REASON]. We apologize for the inconvenience." And then it would dynamically populate the message with the selected values from the first two dropdowns into a textbox on the HTML form: "Train # 123 has been cancelled due to weather. We apologize for the inconvenience.":
#Html.EditorFor(model => model.AnnouncementText, new { htmlAttributes = new { id = "text" } })
I've tried to do this through javascript with no luck:
$(function () {
var str = document.getElementById("message").innerHTML;
var res = str.replace("[REASON]", model.ReasonName);
document.getElementById("text").innerHTML = res;
});
Clearly, the string.replace method isn't meant for razor statements and I'm wondering if there is a such a method or if I'm going about this the wrong way.
With a little help, I was able to find the answer that worked best for me. I was really close with my first attempt and with a few tweaks was able to get it.
$('#message').on('change', function () {
var selection = $.trim($("#message :selected").text()));
var str = document.getElementById("reason");
var reason = str.option[str.selectedIndex].text;
var res = selection.replace("[REASON]", reason);
$('#text').val(res);
});
Thank you to RajN for the help!

Cannot get correct syntax for #Html.ListBoxFor()

I've a series of #Html components which are built dynamically including ListBoxFor(). With the others I've given them an ID which I then use to populate a model value called inputvalues, which holds the values of each component whenever it changes. This works well but I had to change the original DropDownListFor() for ListBoxFor() but although the new syntax works, I cannot assign it an ID value as I did before without getting a syntax error. The code looks like this..
#if (Model != null)
{
#Styles.Render(BundleConfig.Styles_MultiSelect)
IEnumerable<SelectListItem> filetypes = from filetype in Model.ListOptions
select new SelectListItem
{
Value = filetype.ID.ToString(),
Text = filetype.Name,
Selected = Model.SelectedListOptionID == null ? false : Model.SelectedListOptionID > 0
};
<div class="editor-section">
<div class="label">
#Html.DisplayEditLabel(Model.Label, Model.Required.Value)
</div>
<div class="field large-text-field">
#*Original drop down replaced by ListBoxFor() but with ID
#Html.DropDownListFor(m => m.SelectedListOptionID, new SelectList(Model.ListOptions, "ID", "Name", Model.SelectedListOptionID).OrderBy(l => l.Value), new Dictionary<string, object>{
{"id", "personField_" + Model.ID}})*#
#Html.ListBoxFor(m => m.ListOptions, filetypes, new { #class = "multiselectFileTypes" })
</div>
</div>
}
#Scripts.Render(BundleConfig.Scripts_MultiSelect)
<script>
$("#personField_" + "#Model.ID").change(function () {
cnt++;
var uploadValue = JSON.stringify({
"id": "#Model.ID",
"order": cnt,
"required": "#Model.Required",
"libraryUploadConfigType": 3,
"customFieldTypeID": 5,
"selectedListOptionID": $(this).val()
});
inputValues = inputValues + uploadValue;
});
$(".multiselectFileTypes").multiselect({
noneSelectedText: 'All Options',
minWidth: 230,
selectedList: 6
});
</script>
Although the syntax for the original DropDownlistFor() worked and updated inputvalues the component didn't work. Having changed it to ListBoxFor() the component works but I can't seem to assign the ID 'personField_' without getting an error.
Any help would be appreciated.
I can't see that you try to assign ID in your ListBoxFor helper.
It should be like this:
#Html.ListBoxFor(m => m.SelectedListOptionIDs, filetypes, new { #class = "multiselectFileTypes" })
And SelectedListOptionIDs field of your model should be IList or IEnumerable, or Array of your ID type (probably IList<int>). Then it will work fine on View and bind correct on form POST.
See reply from Stephen Meucke above.

ASP.NET Form Display Form Fields based off section in another field

I'm new to ASP.Net development, MVC 5, and pretty much anything Windows, so I'm sure I'm doing something wrong. I searched around for an answer here and found similar questions but I'm clearly doing something wrong...probably due the answers presuming more knowledge of the environment I'm working in...
What happens is the selected box starts off as "Yes" which I would prefer to be "No", and the fields are displayed no matter.
I suspect I have the javascript in the wrong location and/or am missing something important.
I have a bit of code:
<p>
Are you a Licensee?
#Html.DropDownListFor(x => x.Licensee, new[] {
new SelectListItem() {Text="Yes", Value = bool.TrueString},
new SelectListItem() {Text="No", Value = bool.TrueString} }, new {id = "Licensee"})
#section scripts{ <script type="text/javascript">
$(function ()
{
$('#Licensee').change(function ()
{
var value = $(this).val();
if (value == true)
{
$('#LicName').show();
$('#LicUrl').show();
$('#LicRole').show();
}
else
{
$('#LicName').hide();
$('#LicUrl').hide();
$('#LicRole').hide();
}
});
});
</script> }
<p>Your Licensee Name: #Html.TextBoxFor(x => x.LicenseeName, new { id = "LicName" })</p>
<p>Your Licensee Url: #Html.TextBoxFor(x => x.LicenseURL, new { id = "LicUrl" })</p>
<p>your LIcensee Role: #Html.TextBoxFor(x => x.LicenseRole, new { id = "LicRole" })</p>
</p>
Change
#Html.DropDownListFor(x => x.Licensee, new[] {
new SelectListItem() {Text="Yes", Value = bool.TrueString},
new SelectListItem() {Text="No", Value = bool.TrueString} }, new {id = "Licensee"})
To
#Html.DropDownListFor(x => x.Licensee, new[] {
new SelectListItem() {Text="No", Value = bool.TrueString} }, new {id = "Licensee"}),
new SelectListItem() {Text="Yes", Value = bool.TrueString}
That will help with displaying the value No first.
Also the reason why they always show in the JavaScript is because you are passing in bool.TrueString for each value (Yes and No). You will need to use bool.FalseString for the option "No".
For example:
new SelectListItem() {Text="No", Value = bool.FalseString} }, new {id = "Licensee"}),
Okay, I figured it out using checkboxes from the hints here, and this page in particular Show/hide div if checkbox selected
I put this in the header section of the view page:
function showMe(box, name) {
var chboxs = document.getElementsByName(name);
var vis = "none";
for (var i = 0; i < chboxs.length; i++) {
if (chboxs[i].checked) {
vis = "block";
break;
}
}
document.getElementById(box).style.display = vis;
}
This is the code piece:
<p>
Are you a Licensee?
#Html.CheckBoxFor(x => x.Licensee, new { onclick="showMe('LicenseeYes', 'Licensee')" } )
<div id="LicenseeYes", style="display:none">
<p>Your Licensee Name: #Html.TextBoxFor(x => x.LicenseeName)</p>
<p>Your Licensee Url: #Html.TextBoxFor(x => x.LicenseURL)</p>
<p>your LIcensee Role: #Html.TextBoxFor(x => x.LicenseRole)</p>
</div>
</p>
Thank you all for your help, it sent me down the right path, and it gave me the right starting points to the right searches.
I also changed the function to be because the loop wasn't necessary. The other would work if you had multiple check boxes that you wanted to cause the div section to display:
function showMe(box, name) {
var chkbox = document.getElementById(name);
var vis = "none";
if (chkbox.checked) {
vis = "block"
}
document.getElementById(box).style.display = vis;
}

Add style to html.dropdownlist when using javascript function on change

I want to add background color to this drop down.. how can I do this.. I tried adding new{style="background-color: #fff;"} to the below code.. but this does not seem to working..
<%=Html.DropDownList("dd",
new List<SelectListItem>
{
new SelectListItem{ Text="dd1", Value = "dd1" },
new SelectListItem{ Text="dd2", Value = "dd2" }
}
, new { onchange = "jsfunc()" }
)%>
I tried:
<%=Html.DropDownList("dd",
new List<SelectListItem>
{
new SelectListItem{ Text="dd1", Value = "dd1" },
new SelectListItem{ Text="dd2", Value = "dd2" }
}
, new { onchange = "jsfunc()" }
, new {style="background-color: #fff;"}
)%>
You should avoid using inline styles. I suggest creating a class and the syntax would be
new { #class = "yourclass", #onchange = "jsfunc()" }
I think you had a syntax error, new {#style = "background-color: #fff"}, but you should use a class instead.
Edit
new { #onchange = "jsfunc()", #style = "background-color: #fff"}

Categories