Updating list in view Asp.net mvc razor - asp.net-mvc

I have 2 lists in a view. What I want to do is that pick elements from list1 and update list2 with selected elements everytime I pick one. I tried to use PartialView (I don't know if it's correct approach or not) but I failed. I have a function in controller that fills a list by selected items. What needs to be done is updating the view dynamically. Can you suggest me a roadmap for this?
Update
I forgot to say that I have done this with javascript. But I feel like it's the long way when it comes to some validations (checking duplications etc.)
$(document).ready(function (){
$("#allPlayersList a").on("click", function () {
var options = $(this).clone();
$("#thisWeekList").append(options);
});
});

Just create an html list. See if this link helps. https://codepen.io/alexander-holman/pen/QNQrvz. You can also populate the values from database
Then you can get the selected element by javascript like this
var input = document.getElementById('Something').value;
Update after edited question
You can try something like
var listSelection = document.getElementById('Something').value;
Now you can create an api in the backend which accepts this value and returns a list based on it. Call that Api like this
&.ajax({
url: //url of api
data: {exactNameOfApiParameter : listSelection },
success: function(data){
for (i = 0; i < data.length; i++) {
$('<li>', { text: data[i] }).appendTo($('#list2'));
}
}
})
Make sure that id of second list is list2.

Related

MVC 4 #HTML.DropdownlistFor onchange event needs to send SelectedIndex value

I am using MVC 4 and have an #HTML.DropdownlistFor() which loads the rest of the page based on it's selection. On change of the listbox, I want to reload the page so that it load the correct data. As well there are two other parameters that are needed to load the page correctly.
In Create.cshtml view
#Html.DropDownListFor(model => model.SelectedMissionID, Model.MissionsToDisplay, new { onchange = "ReloadPage();" })
function ReloadPage() {
window.location = '#Html.Raw(Url.Action("CreateEdit", "DailyLog", new { ID = 1, ID2 = 0, dailyLogDate = Model.LogDate }))';
}
Where it says ID = 1, I want the selected index of the DropdownlistFor(SelectedMissionID), how do I get this?
I'm not sure if this is the best way to go to the controller, or if I should use a JQUERY .ajax post, is there a better way?
I seems something ideal for an ajax post.
What you have done is OK, inside the ReloadPage() function, just get the selected value in the DropDown, do the Ajax call passing the parameters, and in the success callback put your returned HTML in some container.
The idea is that you replace a part of your view with the return of your Ajax call, not all the page.
To get the selected value, using jQuery:
var selectedValue = $("select[name='SelectedMissionID']").val();
And that can be placed in your ReloadPage() function.
$.post( "your action URL", { ID: selectedValue, OtherParam: "xxxxx" })
.done(function( data ) {
alert( "Data Loaded: " + data );
//here you need to get the HTML, and put in a container
});

ajax request php class function

i have content listed in a div and i have a dropdown with various options to order and filter that content.
I'm using ajax to filter/order that content and is working but i use other php page with the content i want on the div that has the content, like this
function order(str){
$.post("order_products.php",
{
q: str,
},
function(data, status){
document.getElementById("txtHint").innerHTML = data;
});
}
What i wanted was to instead of putting the code (data) to change in another page just for that, i could put that code inside a class php function that i have.
<?php
class products{
function list(){
blablabla
}
That way i would "save space" and organize everything, considering that i have many other things to order/filter but i don't know to to make the ajax request to that function, or if it's possible without having a page in between and then get the response from the function and put it on the div.
You can do this using Laravel by setting up a route to a function that will do the ordering. Please note I've made a lot of assumptions in the following answer as I can't see all your code and have made it quite general, please adjust the code to your project or provide more details of your code if you don't understand the answer fully.
routes.php
Route::post('products/order', [
'as' => 'products.order',
'uses' => 'ProductsController#orderProducts'
]);
Your view (assuming you're using blade)
$txtHint = $('#txtHint'); // grab the reference to txtHint dropdown
$.post( '{{ route("products.order") }}', // hit our route
{
q: str,
},
function(data, status){
$txtHint.empty(); // clear the dropdown
// loop through the data and assign each element to the dropdown
$.each(data, function(value, key) {
$txtHint.append($("<option></option>")
.attr("value", value)
.text(key));
});
});
ProductsController.php
public function orderProducts()
{
$orderBy = \Input::get('q');
return \Products::lists('name', 'id')->orderBy($orderBy);
}
For outside of a framework just change the url to your php file and add in a data attribute for the method you require to be fired from the file.
$.post( 'products.php', // hit our route
{
action: 'order',
q: str,
},
...
Then in products.php you'd do something like this
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'order' : order();break;
case 'otherFunction' : otherFunction();break;
}
}
function order()
{
// order logic here
// get $_POST['q']
// do your ordering
// return data as json
}
See here for similar question: using jquery $.ajax to call a PHP function

How to retain data (form) on custom pagination using MVC?

I have a grid (list generated using scaffolding option) with search criteria. And I created paging concept. I entered search criteria data and search, after post back, I retained the form data using TempData. But, if I click page numbers in grid, the form data not retained and also the grid also getting refreshed.
Is there any way to retain data on pagination?
Thanks!
I added a hidden field dynamically within the form using JavaScript. The page number stored in hidden field, when the user click page number, then submit the form. It is working well without any issue.
Paging:
<button onclick="navigateTo(this, '#Url.RouteUrl("Defined_Route", new { currentPage = j })');">#j</button>
Javascript:
$(function () { //Page Load - Create hidden field, if search button found
if ($("#search")) // Button id
{
var element = document.createElement("input");
element.type = "hidden";
element.id = "currentPage";
element.name = "currentPage";
element.value = '#TempData["Page"]';
if (isNaN(element.value)) element.value = "1";
$(to).parent().append(element);
}
});
function navigateTo(field, url)
{
$("#currentPage").val(field.innerText);
if (isNaN($("#currentPage").val()))
{
location.href = url;//This is for direct url, ie. no search form
}
else
{
$("form").action = url;
$("form").submit();
}
}

BreezeJS - Using expand

I am querying the server to get an entity with expand
function _loadIncidents() {
var deffered = Q.defer(),
queryObj = new breeze.EntityQuery().from('Incidents').expand(['Deployments', 'IncidentComments', 'DTasks', 'ExtendedProperties', 'IncidentEvents']);
dataRepository.fetchEntitiesByQuery(queryObj, true).then(function (incidents) {
var query = breeze.EntityQuery.from("DTasks"),
incidentIds = dataRepository.getEntitiesByQuerySync(query);
deffered.resolve();
}, function(err) {
deffered.reject(err);
});
return deffered.promise;
};
I am getting the results and all is fine, how ever when I query breeze cache to get the entities - I am getting empty collection. So when using expand does the expanded entities are added to the cache?
Yes the related entities identified in the expand should be in cache ... if the query is "correct" and the server interpreted your request as you intended.
Look at the payload of the response from the first request. Are the related entities present? If not, perhaps the query was not well received on the server. As a general rule, you want to make sure the data are coming over the wire before wondering whether Breeze is doing the right thing with those data.
I do find myself wondering about the spelling of the items in your expand list. They are all in PascalCase. Are they these the names of navigation properties of the Incident type? Or are they the names of the related EntityTypes? They need to be former (nav property names), not the latter.
I Had problem with the navigation property - as I am not using OData webapi not using EF , there is problem with the navigation properties so for the current time i just wrote
Object.defineProperty(this, 'Deployments', {
get: function () {
return (this.entityAspect && this.entityAspect.entityManager) ?
this.entityAspect.entityManager.executeQueryLocally(new breeze.EntityQuery("Deployments").
where('IncidentID', 'eq', this.IncidentID)) :
[];
},
set: function (value) { //used only when loading incidents from the server
if (!value.results) {
return;
}
var i = 0,
dataRepository = require('sharedServices/dataRepository');
for (i; i < value.results.length; i++) {
dataRepository.addUnchangedEntity('Deployment', value.results[i]);
}
},
enumerable: true
});

ASP.NET / MVC HTML ActionLink - how to pass returned Javascript value to ActionLink routeValue parm?

(target framework is 4.0)
I am implementing a feature to delete multiple records in a simple table. In order to do this, I am using simple HTML checkboxes with a Javascript function to loop through each one to find which are selected. The Javascript is returning an array of int values representing the record IDs to delete.
I am using an ActionLink to call all of this, and to ultimately return to the Delete function (with an int array as a parm) in my controller file to actually submit the deletions to the database.
My problem is, I don't know how to take the array I get back from the Javascript to place into the ActionLink, to pass it into the controller.
Here is the code with which I am working:
<p>
#Html.ActionLink("Add New", "Add") | #Html.ActionLink("Delete Selected", "Delete", new { id = "???" }, new { onclick = "return getProjectsToDelete()" })
</p>
<script type="text/javascript">
function getProjectsToDelete() {
var answer = confirm("Are you sure you wish to delete the selected projects?");
if (answer) {
var listToDelete = new Array();
var arrayCount = 0;
for (i = 0; i < document.projectList.deleteProject.length; i++) {
if (document.projectList.deleteProject[i].checked) {
listToDelete[arrayCount] = document.projectList.deleteProject[i].value;
arrayCount++;
}
}
return listToDelete;
}
}
</script>
If I understand you correctly, you want to know how to push back a collection of IDs to a controller?
In general, this would be done as a FORM and POST the form to the back end. I myself prefer to do this via AJAX but thats just me.
While you can do this using a GET and stuffing all of the IDs in the query string, its dirty!
It would look something like /controller/action?id=7&id=8&id=9
The Model Binder in .NET will convert that in to a List<int> or int[].
I would suggest using ".push" in Javascript to manage you array of IDs. You can also use the ".join" method on your array to create a clean querystring.

Resources