Mvccontrib grid export to excel - asp.net-mvc

I'm using mvccontrib grid to show seach result data and export to excel.
I have found this article for exporting data to excel and implemented successful.
In my solution, My gridview have a checkbox column that support user select number of row that they want to export then export to excel.
Please suggest me solutions how to do this. Thanks in advance

I've already solved my problems. I've used a form tag which post to my Export controller.
Inside the form tag I used an hidden field which store my array of ID that I've checked on the grid. Then I called submit the form using javascript to post hidden field string to Export controller. On the controller, I've parsed Id into array then query to get specified my records wanted to export. Below is summary my result.
<%using (Html.BeginForm("Export", "Test", FormMethod.Post, new {id="frmPost" }))
{ %>
<%=Html.Hidden("cmdListID")%>
....
<%} %>
javascript:
$('#cmdExport').click(function () {
var jsonObj = [];
var strData = "";
$('input[name="SelList"]:checked').each(function () {
jsonObj.push({ key: $(this).attr('id') });
});
var postData = { "listID": jsonObj };
if (jsonObj.length > 0) {
strData = JSON.stringify(postData);
$('#cmdListID').val(strData);
}
$('#frmPost').submit();
$('#cmdListID').val('');
});
Export controller: I created a list object(using serialize json) for parsing my expected list object.
Finally, I queried into database again by filtering using those IDs that I got to receive my expected records.
Hope this help.

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.

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.

ASP .net MVC Jqgrid data binding

I am using a jqgrid with a column named 'Comments'. My controller code returns data as follows:
var jsonData = new
{
rows=
....
....
select new
{
col1....
col2....
Comments = _Model.GetComments(id),
})
.......
.....
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
_Model.GetComments(id) will return a ClientComments Object which has a few properties say CommentID, FirstName, MiddleName etc., which will be bound to each row in the grid
Now in my jqgrid I need to build a tool tip based on Comments column properties and for that I need to use the properties of my Comments in JQGrid for each row. May I know How I can manipulate Comment's properties for each row? Any help would be appreciated.
I tried in my javascript that for each row rowObject.Comments.FirstName and it did not work.
For the JavaScript version of the grid you would use getDataIDs to get the ID of each row, and then use getRowData to read the data at that row. For example:
var ids = $("#grid").getDataIDs();
for(var i=0; i<ids.length;i++){
var rowdata = $("#grid").getRowData(ids[i]);
// Build tooltip here using rowdata.FirstName, rowdata.MiddleName, etc.
}
But, are you working with the JavaScript version of jqGrid or jqGrid ASP.NET component?

Resources