Use jQuery Select2 with ASP.NET MVC - c#

I'm trying to use Select2 in Razor in ASP.NET MVC. But I can't get work.
$(document).ready(function () {
$(".genreOptions").select2({
tags: true,
ajax: {
url: 'http://localhost:65148/NewProfile/Genres',
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
var newData = [];
$.each(data, function (index, item) {
newData.push({
id: item.Id, //id part present in data
text: item.Genre //string to be displayed
});
});
return { results: newData };
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1
});
#Html.DropDownListFor(x => x.BandProfile.Genres, Enumerable.Empty<SelectListItem>(), new { #class="genreOptions", multiple = "multiple", style ="width: 100%;"} )
The searching for tags works fine. But when I post the form, the count of the input field Is 0. How can I capture the data from the input form?

#Bryan I build up a javascript array and pass it with ajax to the server. Seems to work ok for my purposes. Perhaps you could try that. The selectors I put below will be different than what you need but here is the general idea...
On Click
$('#submitButton').click(function () {
fillHiddenInput();
var dataToSend = $('#hiddenInput').val();
//Submit the form with ajax or however you want to get dataToSend to server
});
FillHiddenInput function...
var fillHiddenInput = function () {
$('#hiddenInput').val("");
var stuff = [];
$('.ms-selection .ms-list li ul').children('li').each(function (){
if ($(this).hasClass('ms-selected'))
{
stuff.push($(this).children('span').text());
}
});
$('#hiddenInput').val(stuff);
}

Related

The result from autocomplete are not displayed in partial view

I am using an ASP.NET MVC web site written in C#. I have code for an autocomplete that works fine in a regular view but not in a partial view. In the partial view,the results are sent back from the controller and the data is there but it is not displayed for the text box in the partial view.
The following is the Javascript code:
$(document).ready(function () {
$("#SearchBox1").autocomplete({
source: function (request, response) {
//alert(request.term);
$.ajax({
url: "/MArrangement/EventDetailAutoView",
type: "POST",
dataType: "json",
async: false,
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
//alert(item.CityName);
return { label: item.CityName, value: item.CityId };
}))
}
})
},
error: function (response) {
alert('1a');
alert(response.responseText);
},
failure: function (response) {
alert('2b');
alert(response.responseText);
},
messages: {
noResults: "", results: ""
}
});
});
This is the partial view:
<div>
<label>Search by Item or Inventory Type</label><br />
#Html.EditorFor(m => m.City.CityName, new { htmlAttributes = new { id = "SearchBox1", style = "position:absolute; z-index:11" } })
</div>
This is the controller code:
[HttpPost]
public JsonResult EventDetailAutoView(string Prefix)
{
List<Models.City> ObjList = new List<City>();
Models.Mod.InventoryMain.getInventory(ref ObjList, Guid.Parse(Session["UserID"].ToString()));
var CityList = (from N in ObjList
where N.CityName.ToLower().Contains(Prefix.ToLower())
select new { N.CityName, N.CityId }).ToList();
return Json(CityList, JsonRequestBehavior.AllowGet);
}
The method EventDetailAutoView is being called and is returning the correct data. In the success portion of the Javascript code, the data is shown (I put in a alert statement to see the data) but the results are not displayed underneath the SearchBox1 text box. The following code works fine in a regular view but not in a partial view.
You should add same code in regular view once partial view loads successfully.
var strUrDomainNamel = + '/Controller/Method';
$.ajax({
url: strUrl,
cache: false,
data: {},
type: 'POST',
success: function (data) {
$(".partialLoadview").html(data);
$("#SearchBox1").autocomplete({
//Your code for autocomplete must be here.
});
},
error: function (req, status, error) {
alert('error message');
}
});

How to refresh a particular division while using MVC

I have tried different ways to refresh a particular division in MVC.
1. Using HTML Action Link
2. Ajax Action Link
3. method
Please help me resolve this issue.
My Code is as follows:
<script src="~/scripts/jquery.unobtrusive-ajax.js"></script>
<script>
function updateAsyncCategoryUpdate() {
var url = '/Home/HomePage';
$.ajax({
url: url,
//data: { value: '1234' }, //if there are any parameters
dataType: "html", //or some other type
success: function () {
window.location.reload(true);
// or something in that area, maybe with the 'data'
},
error: function () {
//some derp
}
});
}
</script>`
#Ajax.ActionLink(item.Name, "HomePage", new { CATEGORy = item.Name }, new AjaxOptions {HttpMethod="GET", OnSuccess = "updateAsyncCategoryUpdate('item.Name')" })
You can append the success function.
This replaces content of div
success: function (data)
{
$('#divSelector').html(data);
}
This appends content of div
success: function (data)
{
$('#divSelector').append(data);
}
Your script function does not have parameter and you send Item.Name to it.(although you dont use this parameter inside the script!)
First, define parameter for updateAsyncCategoryUpdate function.
Secomd,Add a container element(like div) to your page with specific id(resultDiv for example) and replace the success code of your scrip with this:
success: function(result){
var myDiv = $('#resultDiv');
myDiv.empty();
myDiv.prepend(result);
}

Knockout ViewModel Update

I am new to Knockout and I am trying to update my ViewModel from an ajax call. This is what I have right now:
LoanDeductions.js
var deductionLine = function (deductionID, deductionName, amount) {
self = this;
self.deductionID = ko.observable(deductionID);
self.deductionName = ko.observable(deductionName);
self.amount = ko.observable(amount);
};
function LoanDeductions(deductions) {
var self = this;
self.loanDeductions = ko.observableArray(ko.utils.arrayMap(deductions, function (deduction) {
return new deductionLine(deduction.deductionID, deduction.deductionName, deduction.amount)
}));
// Operationss
self.removeLine = function (line) { self.loanDeductions.remove(line) };
};
and this is my scripts in my view:
#section scripts
{
<script src="~/Scripts/koModel/LoanDeductions.js"></script>
<script type="text/javascript">
var updateValues = function () {
$.ajax({
'url': '#Url.Action("UpdateDeductionValues","LoanApp")',
'data': { amount: $('.LoanAmount').val() },
'success': function (result) {// update viewmodel scripts here}
});
var viewModel = new LoanDeductions(#Html.Raw(Model.CRefLoansDeductions2.ToJson()));
$(document).ready(function () {
ko.applyBindings(viewModel);
$('.datepicker').datepicker();
$('.LoanAmount').change(function () {
updateValues();
};
});
});
</script>
}
So, in my view, I have a dropdown list with class name "LoanAmount" which when value is changed, it will perform an ajax call, send the selected loanAmount value to the server, recompute the deduction amounts, then the server returns a jsonresult that looks like this:
"[{\"deductionID\":1,\"deductionName\":\"Loan Redemption Fee\",\"amount\":53.10},{\"deductionID\":2,\"deductionName\":\"Document Stamp\",\"amount\":9.00}]"
Now what I wanted to do is use this json data as my new viewModel.
Can anyone show me the way how to do this, please note that I manually mapped my viewmodel and didn't used the ko mapping plugin.
Any help will be greatly appreciated. Thank you, more power!
EDIT (in response to Fabio)
function updateData() {
$.ajax({
url: '#Url.Action("UpdateDeductionValues","LoanApp")',
data: { amount: self.selectedLoanAmount() },
success: function (deductions) {
//load your array with ko.utils.arrayMap
ko.utils.arrayMap(deductions, function (deduction) {
return new deductionLine(deduction.deductionID, deduction.deductionName, deduction.amount)
});
}
});
}
Not sure If I understood your problem, but if you want to change model values outside of the class, you need to do something like this:
$(document).ready(function () {
var viewModel = new LoanDeductions(#Html.Raw(Model.CRefLoansDeductions2.ToJson()));
ko.applyBindings(viewModel);
$('.datepicker').datepicker();
function updateValues() {
//do you ajax call
//update the model using viewModel.loanDeductions(newItens);
};
$('.LoanAmount').change(function () {
updateValues();
};
});
EDIT 1 - Just to show how to use knockout without jquery.change
function LoadDeductions() {
//declare you properties
var self = this;
self.loanAmount = ko.observable('initialvalueofloanamount');
self.loanDeductions = ko.observableArray();
//create a function to update you observablearray
function updateData() {
$.ajax({
url: '#Url.Content('yourActionhere')' or '#Url.Action('a', 'b')',
data: { amount: self.loadAmount() },
success: function (deductions) {
//load your array with ko.utils.arrayMap
}
});
}
//everytime that loanAmount changes, update the array
self.loanAmount.subscribe(function () {
updateData();
});
//update values initializing
updateData();
};
$(function() {
ko.applyBindings(new LoadDeductions());
});
Bind the select in the HTML
<select data-bind="value: loanAmount"></select>
EDIT 2 - To your second problem
function updateData() {
$.ajax({
url: '/LoanApp/UpdateDeductionValues', //try to write the url like this
data: { amount: self.selectedLoanAmount() },
success: function (deductions) {
//load your array with ko.utils.arrayMap
self.loanDeductions(ko.utils.arrayMap(deductions, function (deduction) {
return new deductionLine(deduction.deductionID, deduction.deductionName, deduction.amount)
}));
}
});
}
Your success handler should look like this.
function(result){
self.loanDeductions(result);
}
Unless you are trying to append in which case it would be
self.loanDeductions(self.loanDeductions().concat(result));

How to display the value in dropdown using jquery?

i have a dropdown, where i can select AgencyName, with that selected AgencyName, i tried to display its AgentName in the next dropdown. But my code does'nt display the AgentName in the next dropdown.
i have my view page like:
<span class="LabelNormal">Agency</span>
#Html.DropDownListFor(m => m.LightAgencies.agencykey, new SelectList(Model.LightAgencies.Agency, "Key", "Value"), "", new {#id = "OwnerAgency" })
<span class="LabelNormal">Agent</span>
#Html.DropDownListFor(m => m.LightOwnerAgent.au_key, new SelectList(""), "", new { #id = "OwnerAgent" })
And i have my jquery like,
$(document).ready(function () {
$("#OwnerAgency").change(function () {
var procemessage = "<option value=`0`> Please wait...</option>";
$("#OwnerAgent").html(procemessage).show();
var url = "/Index/GetOwnerAgent/";
// Get agency key
var OwnerAgency = $("#OwnerAgency :selected").val();
// Get agent
var OwnerAgent = $("#OwnerAgent :selected").val();
$.ajax({
url: url,
data: { agencykey: OwnerAgency },
cache: false,
type: "POST",
success: function (data) {
var OwnerAgent = $("#OwnerAgent :selected").val();
alert(OwnerAgent);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
where my controller "/Index/GetOwnerAgent/" giving the exact value for OwnerAgent. As iam the beginner i dont know how to do this, Kindly tell me.
In your code, you display the selected value in the dropdownlist as soon as the controller responds. I think you want to select the result from the controller in the dropdown.
Assuming that the data returned from the controller is a value that exists in the dropdownlist, you should be able to use:
...
success: function (data) {
$("#OwnerAgent").val(data);
}
...

jQuery autocomplete rendering results that are hidden

I'm trying to use the autocomplete widget in jQuery however when I start typing nothing shows up below it. I can tell it's doing something becasue as I type I can see the scroll bar on the page changing as the list gets shorter, but I can't see the results. My code is below. Any help is appreciated with this.
My controller method looks like this:
public ActionResult GetUsers(string query)
{
var empName = from u in HomeModel.CombineNames()
where u.StartsWith(query)
select u.Distinct().ToArray();
return Json(empName);
}
My View looks like this:
<script type="text/javascript">
$(document).ready(function() {
$("input#autocomplete").autocomplete({
source: function(request, response) {
$.ajax({
url: '/Home/GetUsers',
type: "POST",
dataType: "json",
data: { query: request.term },
success: function(data) {
response($.map(data, function(item) {
return { label: item, value: item };
}));
}
});
}
});
})
</script>
<input type="text" id = "autocomplete"/>
You are missing a few things, like render item, cache managment.
the code should looks something like this: (assuming your action return an array of string)
var cache = {},lastXhr;
$( "input#autocomplete" ).autocomplete({
minLength: 4,
source: function (request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
var descripcion = new Array();
peticion = $.getJSON('/Home/GetUsers',{ query: request.term }, function (data, status, xhr) {
for (d in data) {
descripcion.push(data[d]);
}
cache[term] = descripcion;
if (xhr === peticion) {
response(descripcion);
}
});
},
select: function( event, ui ) {
$("input#autocomplete" ).val( ui.item);
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item + " </a>" )
.appendTo( ul );
};
Try using the inspection tools of your browser to examine the area where your scroll bar is changing. If the elements are present, you likely need to make some changes to the CSS so your text color is different from the background color (or some other display-related issue).

Categories