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!
Related
I am trying to append a number of dropdowns on Button click.These dropdowns should have proper indexing in its 'name' attribute.
This is the dropdown:-
<div id="dropdownDiv" style="display:none">
<div class="form-group">
#Html.LabelFor(model => model.PropertyInvestors, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.PropertyInvestors, (IEnumerable<SelectListItem>)#ViewBag.Investors, "Select Investor", htmlAttributes: new { #id = "dropdown",#name= "[#].PropertyInvestors", #class = "form-control",#onChange="dropdownChange()" })
#Html.ValidationMessageFor(model => model.PropertyInvestors, "", new { #class = "text-danger" })
</div>
</div>
</div>
This is the JS code that I am trying in order to clone the dropdown and replace its name attribute with desired indexing.
$('#addDropdown').click(function () {
var index = (new Date()).getTime();
var clone1 = $('#dropdownDiv').clone();
clone1.html($(clone1).html().replace(/\[#\]/g, '[' + index + ']'));
$('#field1').append(clone1.html());
});
Problem:- The dropdowns are being appended as they are clicked but their name attributes are same for all of the dropdowns produced due to which I cant postback the data to the controller.
While this problem can be solved by using dummy code and manipulating the Index no. by using JS, a good method would be to use Html.BeginCollectionItem() by creating a partial view for the dropdown and later making an ajax call to append the partial view to the main view. Refer to the answer HERE
You can replace ID and Name as follows:
$('#addDropdown').click(function () {
var index = (new Date()).getTime();
var clone1 = $('#dropdownDiv').clone();
$(clone1).find('select').attr("id", index);
$(clone1).find('select').attr("name", "PropertyInvestor[" + index +"]");
$('#field1').append(clone1.html());
});
JSFiddler: https://jsfiddle.net/qj24yybe/6/
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.
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;
}
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" />
}
I've implemented Cascading Drop Down Lists on the Create View page of my MVC Asp.NET Application.
Unfortunately, I am having issues with selecting a value that is located in the JavaScript Array. I need to bind the selected value for the use of one of my controllers.
Right now my List populates, but I have no way to select it. Is there a way to move the counties[i] array from my JavaScript to the #Html.DropDownListFor() helper?
Thanks!
JavaScript:
<script src="#Url.Content("~/Scripts/jquery-1.10.2.min.js")"
type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$("#county").prop("disabled", true);
$("#StateLongName").change(function() {
if ($("#StateItems").val() != "Please select") {
var options = {};
options.url = "/County/GetCounties";
options.type = "POST";
options.data = JSON.stringify({ state: $("#StateLongName").val() });
options.dataType = "json";
options.contentType = "application/json";
options.success = function(counties) {
$("#county").empty();
for (var i = 0; i < counties.length; i++) {
$("#county").append("<option>" + counties[i] + "</option>");
}
$("#county").prop("disabled", false);
};
options.error = function() { alert("Error retrieving counties!"); };
$.ajax(options);
} else {
$("#county").empty();
$("#county").prop("disabled", true);
}
});
});
</script>
Controller:
//GET Counties for Cascading Dropdown List
public JsonResult GetCounties(string state)
{
var counties = db.countycigtaxes.Join(db.statecigtaxes,
cc => cc.stateid,
sc => sc.stateid,
(cc, sc) => new
{
cc,
sc
}).Where(co => co.sc.statefullname == state)
.Select(co => co.cc.countyfullname).ToList();
return Json(counties);
}
View Page:
<div class="form-group">
#Html.LabelFor(model => model.StateLongName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.StateLongName, Model.StateItems, "Please select")
#Html.ValidationMessageFor(model => model.StateLongName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CountyLongName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.DropDownListFor(m => m.CountyLongName, )*#
<select id="county"></select>
#Html.ValidationMessageFor(model => model.CountyLongName)
</div>
</div>
I assume you mean the the selected value of the property CountyLongName is not posting back when you submit the form. You have commented out this line
#Html.DropDownListFor(m => m.CountyLongName, )
and used
<select id="county"></select>
If you want the manual version (I do not recommend this), then you need to add a name attribute that matches the property name so it can be bound by the ModelBinder
<select name="CountyLongName" id="county"></select>
But it is better to use the helper and pass it an empty SelectList
Html.DropDownListFor(m => m.CountyLongName, Model.CountryNames)
where Model.CountryNames is a property in you view model that is initialised to an empty SelectList
Note also options.type = "POST"; should be "GET" and the whole AJAX could be simplified to
$.get('#Url.Action("GetCounties","Country")', { state: $('#StateLongName').val() }, function(countries) {...
and theToList() is not required in the JsonResult method
This should set the option selected for you.
$("#county option[value='" + counties[index] + "']").attr("selected", "selected");