MVC 4 #HTML.DropdownlistFor onchange event needs to send SelectedIndex value - asp.net-mvc

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
});

Related

Updating list in view Asp.net mvc razor

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.

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();
}
}

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.

MVC update Dropdownlistfor with jquery

I have a Dropdownlistfor connected to my model. When the page is loaded the model is empty, but I have a button on the page that updates the model. My problem is that my dropdownlist doesn't update.
Markup:
#Html.DropDownList("ddlRaces", new SelectList(ViewBag.Races, "RaceId", "Name"))
<input type="button" id="btnChangeRace" class="btnGo" value=" " />
#Html.DropDownListFor(m => m.Timers, new SelectList(Model.Timers, "TimerId", "StartTime"), "Velg timer:")
Script:
btnChangeRace.click(function () {
url = "/TimeMerger/GetTimers/?raceId=" + ddlRaces.val();
$.get(url);
});
Codebehind:
[HttpGet]
public ActionResult GetTimers(int raceId)
{
var timeMergeModel = new TimeMergerModel();
timeMergeModel.Timers = TimerModel.GetTimers(raceId);
return View(timeMergeModel);
}
$.get(url);
Here you are sending an AJAX request but you are doing nothing in the success callback so nothing will update. There is not even a success callback. So you need to define a success callback:
$.get(url, function(result) {
// result here will represent the value returned by the server
// which in your case is HTML. So here you might need to update
// the relevant portion of your page.
});
Also your DropDownListFor definition is wrong. You are using the same model variable as first and second argument (Model.Timers). The first first argument of this helper should be a scalar property to which you are binding and not a list. It should be:
#Html.DropDownListFor(
m => m.SelectedTimerValue,
new SelectList(Model.Timers, "TimerId", "StartTime"),
"Velg timer:"
)
where SelectedTimerValue would be a property on your view model that will hold the selected value. Also why you are using DropDownList instead of DropDownListFor for the first drop down? The whole idea of a view model is that it will contain all the necessary information so that the view would simply display it.

ASP MVC 2: Jquery modal popup, how to return data

I'm looking into adding a jquery modal popup to my mvc project. I have been looking at http://www.weirdlover.com/2010/05/20/mvc-render-partial-modal-pop-up-via-jquery-and-colorbox-demo/ posting.
My scenario:
I have a page with a few input fields (textbox, checkbox). I want to have a link that will open a modal popup to select an image. I have a control that will display all images and allow the user to select an image. I understand how to open the modal popup following the site listed above.
What I'm not understanding right now is how to return the selected image name (myimage.jpg) to my original pages view and set it to a property on the model with all the other model changes kept intact.
What I have currently:
MyFormController > ActionMethod:ImageSelected(ImageSelectorModel model)
If it is valid, how do I grab my "MyFormModel" (with all other changes), set MyFormModel.ImageName = model.ImageName and call View(myFormModel).
Thanks for your help
Kevin
I would do it with a hidden input field on the main form. when the user clicks an image in the modal popup, use jQuery to handle the click event and assign the value of the image clicked (the filename?) to the hidden input field. if you name the hidden input field correctly, the ModelBinder will automatically bind the filename to your model object, and you won't need to update it manually.
on main form:
<%= Html.HiddenFor( x => x.ImageFileName ) %>
some jQuery:
$("#popup a.candidateImage").click(function() {
$("form input[name=ImageFileName]").value = $("img", this).attr("src");
// probably also close the modal?
}
I didn't test this, but you should get the idea... I would probably also try to show a thumbnail of the file in ImageFileName on the main form if it's been populated.
If the user is uploading an image, I recommend that you check out AJAX Upload: http://valums.com/ajax-upload/. You can grab the image file asynchronously, save it to disk, and return the saved image path (etc.) as a JsonResult. The javascript would look something like this:
new AjaxUpload('image-input', {
action: '/Photo/Add',
onComplete: function (file, response) {
//using Fowler's json2
var photo = JSON.parse(response);
if (photo.IsValid) {
//do what you want with your photo
//photo.Path should contain the saved image's location
}
else {
alert("Sorry. You tried to upload an invalid file.");
}
}
});
And in your Photo controller:
[HttpPost]
public JsonResult Add(HttpPostedFileBase UserFile)
{
if (UserFile == null)
{
//something bad happened, no file
}
string filePath = "/Path/To/Image/Image.jpg";
//this isn't unit test friendly.
//just quick and dirty:
string fullPath = HostingEnvironment.MapPath(filePath);
UserFile.SaveAs(fullPath);
var model = new JsonPhotoAdd
{
IsValid = true,
Path = filePath
};
return Json(model, "text/html");
}
Keep in mind: this is a workaround, as browsers guard against asynchronous file uploads. As such, you might want to consider adding a second page to your form submission process. On that second page, users can handle uploading images with a standard file input field and a form post. http://forums.asp.net/p/1237419/2253919.aspx
I use ASP.NET MVC2 and the NEW VERSION of AjaxUploader:
When I call my Controller:
public JsonResult AddImg(HttpPostedFileBase UserFile)
UserFile is always null...
the script:
function createUploader() {
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader-demo1'),
action: '/Evenement/AddImg',
name: 'UserFile',
});
}
In my view, the form is OK
<% using (Html.BeginForm("AddImg", "Evenement", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ %>
<div id="file-uploader-demo1"></div>
<% } %>
Do you have an Idea ? Many thanks and sorry for my bad english^^ i'm french.

Resources