I'm trying to download an excel file on DropDownChange.
So, below is my dropdown list
<select style="float: right; width: 15%;" id="templateDropDown" class="form-control">
<option value="select">Select</option>
<option value="Movies">Movies</option>
<option value="TV_SHOWS">TV SHOWS</option>
</select>
<label style="float: right;padding: 0.3%">Download Template</label>
Js
<script type="text/javascript">
$("document").ready(function() {
$('#templateDropDown').change(function () {
showSpinner();
var templateType = $('option:selected').val();
$.ajax({
url: '#Url.Action("DownloadTemplate","Download")',
data: { templateType: templateType },
type: 'POST',
success: function(result) {
hideSpinner();
},
error: function() {
}
});
});
});
</script>
And Below is my MVC Controller code
public FileContentResult DownloadTemplate(string templateType)
{
if(templateType == Movies)
{
var fileAllBytes = System.IO.File.ReadAllBytes(Path.Combine(_hostingEnvironment.WebRootPath, "Templates\\Movies.xlsx"));
var filePath = Path.Combine(_hostingEnvironment.WebRootPath, "Templates\\Movies.xlsx");
}else{
var fileAllBytes = System.IO.File.ReadAllBytes(Path.Combine(_hostingEnvironment.WebRootPath, "Templates\\TVSHOWS.xlsx"));
var filePath = Path.Combine(_hostingEnvironment.WebRootPath, "Templates\\TVSHOWS.xlsx");
}
HelperExtensions.GetFileContentTypeProvider(filePath, out var contentType);
return File(fileAllBytes, contentType, "Movies.xlsx");
}
I'm returning the file in bytes,but it is not downloading the file. And I am not getting any runtime error also.Could anyone please tell me where I'm missing.
Thanks in Advance
If you're retrieving the file via AJAX, the simplest answer is not to return the file, but to return the file URL and change the browser location to start a download. Downloading via AJAX is a tricky endeavor.
(As a side note, you don't need the $('document').ready wrapper - $('#templateDropDown') is shorthand for that already.)
$('#templateDropDown').change(function () {
showSpinner();
var templateType = $('option:selected').val();
$.ajax({
url: '#Url.Action("DownloadTemplate", "Download")',
data: { templateType: templateType },
type: 'POST',
success: function(result) {
hideSpinner();
window.location.href = result;
},
error: function() {
}
});
});
Controller:
public string DownloadTemplate(string templateType)
{
if (templateType == Movies)
{
var filePath = Path.Combine(_hostingEnvironment.WebRootPath, "Templates\\Movies.xlsx");
}
else
{
var filePath = Path.Combine(_hostingEnvironment.WebRootPath, "Templates\\TVSHOWS.xlsx");
}
return filePath;
}
Related
I am using bellow code to insert the data to db. While Clicking the save button the data should be bind to the model and needs to be posted to controller action . But the data is not bind to the model. What is the issue in the bellow code . Any please help me to solve the below issue.
#(Html.Kendo().TextBoxFor(model => model.Code)
.HtmlAttributes(new { placeholder = "Enter Code", required = "required",
validationmessage="Code is Required" })
)
<input type="button" title="Save" id="btnsave" value="Save" onclick="submit()"/>
<script>
function submit(data) {
debugger;
console.log("Cosoledata "+JSON.stringify(data))
$.ajax({
type: "POST",
url: '#Url.Action("action", "controller")',
data: { data: #Model },
dataType: "json",
success: function (response) {
}
});
}
</script>
data: { data: #Model },
In the JavaScript script, you can directly get the Model data via the #Model.
To send the model data to the controller method, you could create a JavaScript object, then use JQuery to get the related property value (such as Code), then send the object to the controller method.
Please refer the following sample:
View page:
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$(function () {
$("#btnCreate").click(function () {
var review = {}; //create a JavaScript Object.
//user JQuery to get the entered value, and set the property value.
review.ReviewID = $("#ReviewID").val();
review.MovieID = $("#MovieID").val();
review.goreRating = $("#goreRating").val();
review.shockRating = $("#shockRating").val();
review.jumpRating = $("#jumpRating").val();
review.plotRating = $("#plotRating").val();
review.supernaturalRating = $("#supernaturalRating").val();
review.starRating = $("#starRating").val();
//if you want to send multiple objects, you could create an array.
//var reviewlist = [];
//reviewlist.push(review);
$.ajax({
url: "/Home/AddReview",
method: "Post",
data: { "reviewViewModel": review } , // { "reviewViewModel": reviewlist },
success: function (response) {
alert(response);
},
error: function (response) {
console.log("error");
}
})
});
})
</script>
}
Controller method:
[HttpPost]
public IActionResult AddReview(ReviewViewModel reviewViewModel)
{
if (ModelState.IsValid)
{
//do something
}
return View();
}
The result as below:
I am trying to get jQuery autocomplete in a textbox. But I don't seem to be able to display the data from my JsonResult in the view, I checked with firebug and verfied that the data is transferred from server, just doesn't disply in the TextBox. I don't get any errors.
Here's my code :
public JsonResult search(string term)
{
// string prefixText =SearchString;
var FamilyLastName = _repository.FamilySearch(term);
var data=FamilyLastName.ToList();
return Json(data);//.Select(x => new { label = x, ID = x }));
}
#using (Html.BeginForm())
{
<label for="SearchString">My Autocomplete:</label>
<input class="form-control" type="text" name="SearchString" id="SearchString" autocomplete="off" />
}
<script type="text/javascript">
$(document).ready(function () {
var param = { "searchstring": $("#SearchString").val() };
$("#SearchString").autocomplete({
autoFocus: true,
source: function (request, response) {
// call your Action
$.ajax({
url:'search?term=' + $("#SearchString").val(),
// data:"{'term':'" +$("#SearchString").val() + "'}",
dataType: 'json',
method: "post",
contentType: "application/json; charset=utf-8",
success: function (data) {
return{
label:data.FamilyLastName
};
},
select:
function (event, ui) {
$('#SearchString').val(ui.item.label);
return false;
},
});
},
minLength: 1,// requ
I want to pass this data from my view to save it via controller.
My view
<div>
<b>Title</b> <br />
<input type="text" id="title" /><br />
<b>Description</b> <br />
<input type="text" id="desc" /><br />
</div>
<button id="saveDetails">Save</button>
My js
$(document).ready(function () {
$(document).on("click", "#saveDetails", saveDetails);
$("#detailsPanel").hide();
});
var saveDetails = function () {
var dataPost = {
"Title": $("#title").val(),
"Description": $("#desc").val(),
"AssetId": $("#assetId").val()
}
$.ajax({
type: "POST",
async: false,
contentType: "application/json",
data: JSON.stringify(dataPost),
url: "/Media/Save"
}).done(function (state) {
if (state.Saved == true) {
displayStatusMessage("Saved Successfully");
$("#detailsPanel").hide();
mediaPlayer.initFunction("videoDisplayPane", state.StreamingUrl);
} else {
displayStatusMessage("Save Failed");
}
});
}
My Controller
[HttpPost]
public JsonResult Save(MediaElement mediaelement)
{
try
{
mediaelement.UserId = User.Identity.Name;
mediaelement.FileUrl = GetStreamingUrl(mediaelement.AssetId);
db.MediaElements.Add(mediaelement);
db.SaveChanges();
return Json(new { Saved = true, StreamingUrl = mediaelement.FileUrl });
}
catch (Exception ex)
{
return Json(new { Saved = false });
}
}
Its already post the data to my controller (i saw it via Fiddler), but it always return Json(new { Saved = false }).
Anything wrong with my code? Need help, please...
[Case Closed]
Okay, I found in my db, i have coloumn UploadDate which is not null. And I already declare the default value on my db with this -> getdate(). But it doesnt work when I inserted data from controller. So i add the value of UploadDate manually via Controller. Then Its Works:)
Thanks everybody :)
i think the problem is with the MediaElement model binding ...
but before, check the folowing :
you can try to remove the JSON type of your ajax.
your json format.
the dataPost var miss the ; end.
$(document).ready(function () {
$(document).on("click", "#saveDetails", saveDetails);
$("#detailsPanel").hide();
});
var saveDetails = function () {
var dataPost = {
Title: $("#title").val(),
Description: $("#desc").val(),
AssetId: $("#assetId").val()
};
$.ajax({
type: "POST",
async: false,
data: dataPost,
url: "/Media/Save"
}).done(function (state) {
if (state.Saved == true) {
displayStatusMessage("Saved Successfully");
$("#detailsPanel").hide();
mediaPlayer.initFunction("videoDisplayPane", state.StreamingUrl);
}
else {
displayStatusMessage("Saved Failed");
}
});
}
Ajax post:
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function () {
// var vals = [];
// $('input:checkbox[name=Blanks]:checked').each(function () {
// vals.push($(this).val());
// });
// alert(vals);
//
var checkboxData = $(':checked').val();
$.ajax({
// Check the value.
type: 'POST',
url: '/Home/Extract',
data: { 'name': checkboxData },
// contentType: 'application/json; charset=utf-8', // No need to define contentType
success: function (result) {
},
error: function (err, result) {
alert("Error in delete" + err.responseText);
}
});
});
Controller method:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Extract(string[] name)
{
}
My problem is that I am getting null values in my string[] name when I use array and single checkBox values when I use other case. Any suggestions or ideas as to why the post looks good?
View:
<input type="button" id="btn" value="Extract" style="float:right "/>
#foreach (var m in (List<string>)ViewData["list"])
{
<ul>
<li>
<input type="checkbox" class="myCheckbox" name="Blanks" id="chk" value="#m"/>
<img src="#m" alt=""/>
First start by fixing your markup and remove the id="chk" from your checkboxes because you cannot have 2 elements with the same id.
Alright, and then simply generate a javascript array containing the values of the selected checkboxes and POST this array to the server:
$('#btn').click(function () {
var values = $('input[type="checkbox"].myCheckbox:checked').map(function() {
return $(this).val();
}).toArray();
$.ajax({
type: 'POST',
url: '/Home/Extract',
data: JSON.stringify({ name: values }),
contentType: 'application/json',
success: function (result) {
},
error: function (err, result) {
alert("Error in delete" + err.responseText);
}
});
return false;
});
And your controller action signature might look like this:
[HttpPost]
public ActionResult Extract(string[] name)
{
...
}
But all this would have been completely unnecessary if you had used a view model and the strongly typed Html.CheckBoxFor helper.
Can I post to action from view a filed of of my model ? Is is not part of the form. I just want to pass the myModel.someValue as argument to nextRelease action, hopefully without putting it anywhere in the form.
e.g.
View:
#model myModel
#using (Html.BeginForm("Search", "News", FormMethod.Get, new { id = "myform" }))
{
<div>myModel.someValue</div> //to show it has this field
<script type="text/javascript">
$('#nextbutton').click(function () {
$('#myform').attr("action", "/#controller.Language/news/nextRelease");
$("#submit").click();
});
</script>
}
Sure, you could use AJAX:
#model myModel
<script type="text/javascript">
$(function() {
$('#nextbutton').click(function () {
var url = '#Url.Action("NextRelease", "News")';
var dataToPost = #Html.Raw(Json.Encode(new { someValue = Model.SomeValue }));
$.post(url, dataToPost, function(result) {
alert('data successfully posted to server');
});
return false;
});
});
</script>
<button id="nextbutton">Next button</button>
or if you wanted to post not only a single property but the entire model:
var url = '#Url.Action("NextRelease", "News")';
var dataToPost = #Html.Raw(Json.Encode(Model));
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(dataToPost),
success: function(result) {
alert('data successfully posted to server');
}
});