Pass javascript value to controller C# - c#

I have created a search function on my website that allows the user to select what table they wnat to search for. The select list is within a dropdown rendered within a dropdown menu using bootstrap. The issue I'm facing is that when the form is run the value of the selected item from the dropdown menu that is passed into the controller is "" instead of the value that was selected in the dropdown menu.
Any help would be grateful.
** search function**
<div class="col-lg-6">
#{using (Html.BeginForm("Results", "Searchv2", FormMethod.Get))
{
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">Action <span class="caret"></span></button>
<ul class="dropdown-menu">
#foreach (var searchType in new[] { "User", "Restaurant", "Cuisine" })
{
<li>#searchType</li>
}
</ul>
<input type="hidden" name="SearchBy" />
</div>
<input type="text" class="form-control" placeholder="Search" name="SearchString" id="SearchString">
</div>
}}
</div>
jquery that finds the value
<script>
$(".dropdown-menu").click(function () {
$("input[name='SearchBy']").val($(this).html());
});
</script>

you have to write click event on anchor tag, as you have anchor tag inside <li> like this:
<ul class="dropdown-menu">
<li>
<a>SearchText</a>
</li>
</ul>
$(".dropdown-menu li a").click(function () {
$("input[name='SearchBy']").val($(this).html());
});

I believe you want to set the SearchBy value by getting the value of the selected item:
<script>
$(".dropdown-menu").click(function () {
$("input[name='SearchBy']").val($(this).val());
});
</script>

if you want to get the value of text in between the <a></a> tags, try use .text() instead of html()

First you are selecting the ul not the a inside its li and second you should use jquery text function:
<script>
$('.dropdown-menu li a').click(function (e) {
e.preventDefault();
$('input[name="SearchBy"]').val($(this).text());
});
</script>

Related

Disable Div Contents Based on checkbox value using jquery

hi am developing mvc project using c#
currently am working on employee system model
I have designed view below like this
#Html.CheckBoxFor("value", new {data_divToDisable="SSLCSection",#class="SelectSection" })
<div id="SSLCSection" class="DisableDiv">
<table>
//Conntent goes here
</table>
</div>
#Html.CheckBoxFor("value", new {data_divToDisable="PUCSection",#class="SelectSection" })
<div id="PUCSection" class="DisableDiv">
<table>
//Conntent goes here
</table>
</div>
#Html.CheckBoxFor("value", new {data_divToDisable="GraduationSection",#class="SelectSection" })
<div id="GraduationSection" class="DisableDiv">
<table>
//Conntent goes here
</table>
</div>
#Html.CheckBoxFor("value", new {data_divToDisable="PostGraduationSection",#class="SelectSection" })
<div id="PostGraduationSection" class="DisableDiv">
<table>
//Conntent goes here
</table>
</div>
here I need to disable sections when loading view based on checkbox value
like if checkbox is checked no need to disable that section otherwise it would be disable
I have written jquery like this
$(document).ready(function () {
$(".SelectSection").attr('checked', false,function(){
var id = $(this).find(".DisableDiv");
alert(id);
$(this).find(".DisableDiv").find('input, textarea, select,table').each(function () {
$(this).prop('disabled', true);
});
});
this is not doing anything for us
please help and your help would be greately appreciated
Please Note I have using data-Attribute to simplify the jquery and while each time loading the page it has to disable the sections based on checkbox value (hint:it has to disable if checkbox value is false )
You could try the follow, excuse the pseudo code.
HTML
<input class="SelectSection" type="checkbox" >hello1</input>
<div id="SSLCSection" class="DisableDiv" >
<input type="input">Test</input>
<textarea>Test1</textarea>
</div>
<br>
<input class="SelectSection" type="checkbox">hello2</input>
<div id="PUCSection" class="DisableDiv" >
<input type="input">Test2</input>
<textarea>Test12</textarea>
</div>
<br>
<input class="SelectSection" type="checkbox" checked>hello3</input>
<div id="PostGraduationSection" class="DisableDiv" >
<input type="input">Test3</input>
<textarea>Test3</textarea>
</div>
jQuery
$(document).ready(function () {
$(".SelectSection[type='checkbox']").each(function (i, o) {
if ($(o).is(":checked")) {
$(o).next('div').find('input,textarea').each(function (i, o) {
$(o).prop('disabled', true);
});
}
});
})
The above assumes that your next element after the relevant checkbox is the div in question which holds the elements that need to be disabled.

Changing value of my hidden field with Javascript

I'm having a hard time understanding this code that I was given to work on as I am a newbie at Javascript/HTML/C# Razor
Currently I have the following
<li class="control-group">
<label for="autoReload" class="control-label">Auto Reload</label>
<div class="controls">
<div class="btn-group radioButtons radioToggleCollapse" data-toggle-id="#autoReloadExtra" data-toggle="buttons-radio">
<button type="button" data-value="no" class="btn active">No</button>
<button type="button" data-value="yes" class="btn">Yes</button>
</div>
<input type="hidden" class="radioHidden" value="'$'+#(Model.IsAutoReload ? "True" : "False")" id="autoReload" name="IsAutoReload">
</div>
</li>
What I'm looking to do is when I click the button No, change the value in that text box to False, or if I click true then I want that value to be changed to true
I have found the following Javascript,
<script>
$(document).ready(function(){
$("#autoReload").on('change',function(){
if ($(this).val() == 'yes') {
$(".saveCardSwitch button[data-value='true']").trigger('click');
$(".saveCardSwitch button").each(function(){
$(this).addClass('disabled').prop('disabled',true);
});
}
if ($(this).val() == 'no') {
$(".saveCardSwitch button").each(function(){
$(this).removeClass('disabled').prop('disabled',false);
});
}
});
});
</script>
Now I've tried switching the actual data-values on my buttons to true/false, but when I do that the hidden message that I have open doesnt show anymore so I'm kind of stuck at this point. I'd also like to clarify, when I call #(Model.IsReload ? "True" : "False" that passes the value back to my controller in the post method right?
As you are using Jquery, You can do it the following way:
$('.btn').click(function(){
$('.radioHidden').val($(this).attr('data-value') === 'yes');
});
Fiddle
From what I understand all you need is a function to set a value on a specific element. You can do that with the following code
<li class="control-group">
<label for="autoReload" class="control-label">Auto Reload</label>
<div class="controls">
<div class="btn-group radioButtons radioToggleCollapse" data-toggle-id="#autoReloadExtra" data-toggle="buttons-radio">
<button type="button" data-value="no" onclick="setValue(false, 'autoReload');" class="btn active">No</button>
<button type="button" data-value="yes" onclick="setValue(true, 'autoReload');" class="btn">Yes</button>
</div>
<input type="hidden" class="radioHidden" value="" id="autoReload" name="IsAutoReload">
</div>
and your function setValue can be something like:
var setValue = function(value, id)
{
var domEl = document.getElementById(id);
domEl.value = value;
}
You don't appear to have any events bound to the buttons that you want to use to toggle that is the first thing you need, an onclick event you can do this
<button type="button" data-value="no" onclick="updateHidden(this.dataset.value)" class="btn active">No</button>
<button type="button" data-value="yes" onclick="updateHidden(this.dataset.value)" class="btn">Yes</button>
then the code to update the hidden input is
function updateHidden(value){
value = value==="yes"?"TRUE":"FALSE";
document.getElementById("autoReload").value = value;
}

Refresh images jquery

I have uploading images with ajax form in my ASp.Net application. I need to refresh images, so I try this:
$(function () {
$(".fileUploadForm").ajaxForm({
success: function (data, text, xhr, form) {
var tmp = jQuery(this).closest("img[class=imageResource]").attr('src');
}
});
});
Here is my image:
<img class="imageResource" alt="picture" src="#Url.Action("Picture", new { id = Model.Id })" />
How can I find and rewrite image source with the same name
Update
Here is my html:
<div class="thumbnail">
<a target="_blank" href="/Template/OriginalPicture/8b8c824b-9605-4931-9fe2-1f5979baca42">
<img class="imageResource" src="/Template/Picture/8b8c824b-9605-4931-9fe2-1f5979baca42" alt="picture">
</a>
<div class="caption">
<div style="margin-bottom: 5px;">
<form class="form-horizontal fileUploadForm" method="post" enctype="multipart/form-data" action="/Template/PictureResource?resourceId=8b8c824b-9605-4931-9fe2-1f5979baca42&configId=aa383b5a-23b2-4780-965e-ef4e95cd3fa2&pageNumber=1">
<div class="input-append">
<input type="file" name="picture">
<input class="span1" type="text" size="128" style="width: 86px;">
<button class="btn browse" type="button"> ...</button>
<button class="btn" type="submit">Upload</button>
</div>
</form>
</div>
</div>
try this code:
$(function () {
$(".fileUploadForm").ajaxForm({
success: function (data, text, xhr, form) {
var tmp = form.closest('.thumbnail').find('.imageResource').attr('src');
form.closest('.thumbnail').find('.imageResource').attr('src', tmp + "?" + (new Date()).getTime());
}
});
});
I'm not sure if jQuery(this) will return a form (do not remember what is "this" there )
(new Date()).getTime() - is just to change image URL and force brower take image not from cache. Uh. And not noticed .closest - it will search for closest parent, and not for a child element. You may use .find for that.
form - that is a current from, according to docs closest('.thumbnail') will find parent with class .thumbnail closest to a form. .find('.imageResource') will search for an elements with class imageResource only inside .thumbnail. As there is only one image tag with class imageResource inside thumbnail - code above should work fine

How to bind a List<string> in MVC?

I'm searching for a good way to bind a List<string> to a form in MVC3. Right now I have 2 options:
Use a ListBox with a textbox, add/delete button in jquery and do a select all items before posting my form
Use a <li> that will contains a <input type="hidden" /> with the value also with a add/delete button in jquery
I'm sure there is easyer way to do this but I did not found anything here so I'm asking for help. My concern is to add different bussiness units (string) to a company while editing the company other properties (name, address..).
Thanks!
Using a ListBox seems like a good way to achieve that. Then you could have a textbox and an add button next to it that will append a new element to the listbox and a delete button that will remove the selected items from the ListBox all using client side jquery. And when the form is submitted, since you have used a ListBox (<select> with multiple="multiple") it will automatically bind to a property on your view model of type List<string> and you will be able to fetch the selected values.
Here's my code for the first option, if anyone find a better solution, let me know!
Html/Razor :
<div class="row">
<div class="span12">
<div class="control-group">
<label for="AddBusinessUnit" class="control-label">#Strings.BusinessUnit</label>
<div class="controls">
<div class="input-append">
<input type="text" class="span2" size="16" id="AddBusinessUnit" />
<button class="btn" type="button" id="add-business-unit">#Strings.Add</button>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
#Html.ListBoxFor(model => model.BusinessUnits, SelectLists.BusinessUnits(Model.BusinessUnits, false), new { Multiple = "multiple" })<br/>
#Strings.DeleteSelectedElement
</div>
</div>
</div>
</div>
<div class="form-actions">
<input type="submit" class="btn btn-primary" value="#Strings.Save" />
#Strings.Cancel
</div>
Js :
<script type="text/javascript">
$(document).ready(function () {
$('#add-business-unit').click(function (e) {
var bu = $('#AddBusinessUnit').val();
if (bu != '') {
$('#BusinessUnits').append($('<option></option>').val(bu).html(bu));
$('#AddBusinessUnit').val('');
}
e.preventDefault();
});
$('#delete-business-unit').click(function (e) {
$('#BusinessUnits :selected').remove();
e.preventDefault();
});
$('input[type="submit"]').click(function () {
$('#BusinessUnits option').attr('selected', 'selected');
});
});
The SelectList :
public static class SelectLists
{
public static IList<SelectListItem> BusinessUnits(IList<string> bussinessUnits, bool addEmpty, string selected = "")
{
var list = new List<SelectListItem>();
if(addEmpty) list.Add(new SelectListItem());
list.AddRange(bussinessUnits.Select(businessUnit => new SelectListItem {Selected = selected == businessUnit, Text = businessUnit, Value = businessUnit}));
return list;
}
}
It will bind to my property public virtual IList<string> BusinessUnits { get; set; } in my model.
Hope it can helps!

jquery show/hide - start open if condition true

Working on a jQuery show hide box for filter checkboxes on my MVC3 razor page.
I have a page which changes depending on whether these checkboxes are checked or not, but I'd like them to stay open if any of the checkboxes are unchecked.
Currently the show/hide works, but how do I determine whether the page loads with them shown/hidden based on if any checkboxes are checked?
I can return a boolean value to state if any are unchecked or not, and was really looking for a jQuery genius to help me with the best/tidiest way to achieve this.
Here is an example of one of the filters, where modeFilterList is a generic list for each checkbox, containing the name, ID and checked status:
<div id="filterwrap">
<h2 class="filter">Filter your results</h2>
#using (Html.BeginForm())
{
<ul id="filter">
<li>
<h2>
Modes</h2>
<div class="filtercontent">
#foreach (var item in modeFilterList)
{
<div class="radiorow">
#Html.CheckBox("mode_" + item.ID, item.Checked)
#item.Name
</div>
}
</div>
<!-- end of filtercontent -->
</li>
</ul>
}
</div>
This is the jquery code for showing and hiding:
$('#filterwrap li h2').live('click', function (e) {
$(this).next('div.filtercontent').slideToggle() ;
e.preventDefault(); //stops page jumping to top
});
I thought about having a hidden field containing a true/false value just below the h2 that could be read when the page reloads, but there must be a nicer way to do it with jQuery!
you can use Jquery toggle() function or $("componentID").show() or hide() function
Ok, not crazy about the solution I've come to, so if anyone has anything better and tidier, let me know.
So, for each filter, I pass a bool parameter via viewbag to show if any checkboxes have been selected.
bool modeStatus = ViewBag.modeStatus;
I then added a hiddenfield with class:
<div id="filterwrap">
<h2 class="filter">Filter your results</h2>
#using (Html.BeginForm())
{
<ul id="filter">
<li>
#Html.Hidden("mode", modeStatus, new { #class = "filteritem" })
<h2>
Modes</h2>
<div class="filtercontent">
#foreach (var item in modeFilterList)
{
<div class="radiorow">
#Html.CheckBox("mode_" + item.ID, item.Checked)
#item.Name
</div>
}
</div>
<!-- end of filtercontent -->
</li>
</ul>
}
</div>
and this code within the (document).ready
$("input.filteritem:hidden").each(function () {
if ($(this).val() == "True") {
$(this).nextAll('div.filtercontent').show();
}
});

Categories