how to upload a file using jquery + c# - c#

I'm having issues trying to upload a docx file. First, when I click on "Choose File", the prompt opens up but the page reloads going to CheckInController/CheckIn url ( I thought that what you add in the Html.BeginForm is where your controller and method go when you click on submit ). Second thing is how do I know that the contents of the document are being sent to the server and not just the name or id?
https://jsfiddle.net/w6adx6za/1/
<div class="session-filter">
#using (Html.BeginForm("CheckIn", "CheckInController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="select-filter-title"><strong>Select File</strong></div>
<table>
<tr>
<td><input name="fileResume" id="hiddenFileResume" type="file" value="" /><input type="submit" onclick="tested()"/></td>
</tr>
</table>
}
</div>
function tested(){
$.ajax({
cache: false,
type: "POST",
url: "/SummaryStatementProcessing/CheckInSummaryStatement",
data: data
});
}
public ActionResult CheckIn(HttpPostedFileBase fileResume){
//work in here
}
I don't need the page to go anywhere ( because this is actually in a dialog so it can close on submit, but currently it's reloading the page at the url above ). Currently I can't even get to the controller to check...

To do what you require, the easiest method is to send a FormData object in the request. However, you should ideally be hooking to the submit event of the form, not the click of the submit button, to stop the page redirecting.
You'll need to set the processData and contentType properties to false in the request. Also, the Action name does not appear to match your URL. You can fix that by using #Url.Action. The Action also needs the [HttpPost] attribute as that's the HTTP verb you're using in the AJAX request.
With all that said, try this:
<div class="session-filter">
#using (Html.BeginForm("CheckIn", "CheckInController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="select-filter-title"><strong>Select File</strong></div>
<table>
<tr>
<td>
<input name="fileResume" id="hiddenFileResume" type="file" value="" />
<input type="submit" />
</td>
</tr>
</table>
}
</div>
$('.session-filter form').submit(function(e) {
e.preventDefault();
$.ajax({
cache: false,
type: "POST",
url: '#Url.Action("CheckIn", "SummaryStatementProcessing")',
data: new FormData(this),
processData: false,
contentType: false,
});
}
[HttpPost]
public ActionResult CheckIn(HttpPostedFileBase fileResume)
{
// work in here
}
With the above code in place, you should then be able to work with the HttpPostedFileBase class in the Action.

Related

How do I submit a form, but my text boxes preserve their values in asp.net Razor pages

I have a html form in which I write in a text box and submit when press a button and it saves in db but I want the page not to refresh and continue with the values ​​in the text box
I have see people talking about ajax but I have never worked with ajax
<div class="row" style="float:left; margin: 2px ">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="col-md-3">
<div class="form-group">
<label>Pressão Injeção:</label>
<input id="id3" type="text" name="Pressão_de_Injeção" /> <br />
</div>
</div>
Here is a quick example of an AJAX call which will POST data to an controller:
var menuId = $("ul.nav").first().attr("id");
var request = $.ajax({
url: "Home/SaveForm",
type: "POST",
data: {id : menuId},
dataType: "html"
});
request.done(function(msg) {
console.log('success');
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
Note, that you can also pass objects to the controller by supplying them as an variable within the data object:
var menuId = $("ul.nav").first().attr("id");
var obj = {
id: menuId,
text: "Foo"
};
var request = $.ajax({
url: "Home/SaveForm",
type: "POST",
data: {name: "Jim", object: Obj},
dataType: "html"
});
(Code adapted from an answer by apis17.)
An introduction to AJAX, can be found here:
https://www.w3schools.com/js/js_ajax_intro.asp
The only other method of performing what you required (without using AJAX) is to use a form submit and pass the data back to the HTML form once complete. You would then need to re-populate the fields (however, this will cause additional work on both submitting and re-populating, if (and/or when) new fields are adding if the future).
You will have to take the ajax approach.
But if you don't want to do that, you can always post to the controller and return the model to the view. It will have the text you entered into the textbox.eg.
public IActionResult MyView()
{
return View();
}
[HttpPost]
public IActionResult MyView(MyModel model)
{
return View(model);
}
Hope this helps as an alternative.

ASP.NET MVC: Put searching attributes into url (not query string)

have implemented filtering on my ASP.NET MVC 5 app.
My searchbox consists of a few Dropdownlists with predefined values. When the Dropdownlist value changes, the form is submitted and I see all available tickets for a specific method.
After the form submits the page reloads and I see the url like mysite.com/?Method=car. But I would like to get rid of the query string and put car directly into the url, i.e.
mysite.com/method/car or mysite.com/method/plain etc
Is it possible?
Search box
#using (Html.BeginForm("Search", "Transfer", FormMethod.Get))
{
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-10">
#Html.DropDownListFor(model => model.Method, Model.Methods, new { #class = "query"})
</div>
</div>
</div>
<input type="submit" class="hidden" />
}
My action method
[Route("~/transfer/{method?}")]
public async Task<ActionResult> List(string method)
{
//filter and displaying
return View(viewModel);
}
By default Html.BeginForm with FormMethod.Get will serialize all the form values into query string. So if you want friendly URLs you will have to write some JavaScript (jQuery in this example).
First of all you can remove the form
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-10">
#Html.DropDownListFor(model => model.Method, Model.Methods, new { #class = "query"})
</div>
</div>
</div>
<button type="button" id="submitMethodBtn">Submit</button>
<script>
var baseUrl = '#Url.Action("Search", "Transfer")/'
$('#submitMethodBtn').click(function(){
var url = baseUrl + $(#'#Html.IdFor(m=>m.Method)').val();
window.location.href = url;
})
</script>
Some issues/clarifications:
1if you enter mysite.com/method/car (assuming that issue #2 is resolved )in browser it will take you to a correct action so your issue is basically generating friendly Url in the view.
2 In the provided code example i used an inline script. You can extract it to a separate static file but you will have to hard-code the url and the html id for Method property.
3 Your action method gets int as parameter so how do you expect it to work with mysite.com/method/car (car is a string) ?
You can call an ajax method on page which will avoid query string and when controller redirects to ActionResult then again you can call ajax method on redirected page. By this way you can avoid query string in MVC.
Take below code as example.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Transfer/search",
data: "{ID:1}",
dataType: "json",
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
Make return type as JsonResult of controller method.

Mvc: show animated gif for progress while loading big excel file to database

I am loading a big excel file to the database. I want my users to see that there is an activity going on. I started but didn't know how to proceed.
My ActionResult Index method has two parameters. How do I define this in my javascript.
On the click of the submit button I want the animated image to show and then stop when processing is complete
I understand I have to hide the div somehow. Not sure how to do this.
Please assist. Here is my code below.
#model SampleTemplate.Models.ResultViewModel
#{
ViewBag.Title = "Index";
}
<h2>File upload section</h2>
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="uploadSection">
<div id="divloading">
<p style="position:absolute; top:30%; left:45%;color: Red;">
Excel file in process, please wait...<img src="../../Images/animated.gif" />
</p>
</div>
<div>
<p class="headerSection">Select script</p>
<p>
<select name = "genericId">
<option value="12.1">12_1_flat_goods</option>
<option value="12.2">12_2_mats_bm</option>
</select>
</p>
</div>
<div id="spacebetween">
<p class="headerSection">Path to source file: </p>
<p class="spacebelow"><input type="file" name="file" value="" /> </p>
<p><button id="submi" name="Submit" onclick="JavascriptFunction();">Submit</button></p>
</div>
</div>
}
<script type="text/javascript" language="javascript">
function JavascriptFunction() {
var url = '#Url.Action("","Home")';
$("#divLoading").show();
}
</script>
...Here is my method
[HttpPost]
public ActionResult Index(HttpPostedFileBase file, ResultViewModel resModel)
{
//code to upload excel file goes here. No need to show this.
}
I have used Knockout.js for this before, and found it to be really clean and simple.
Check it out here: http://knockoutjs.com/
Your page would look something like this:
Knockout ViewModel javascript file -
function TestViewModel() {
var self = this;
self.itemsToDisplay = ko.observableArray([]);
//this property can be used to hold the bool for when you first hit the upload button
self.uploadStarted = ko.observable(false); // when page is loaded, this is false
//this is a property that will hold the bool value to show/hide the gif after the upload has started
self.uploadCompleted = ko.observable(false); // when page is loaded this is false
ko.applyBindings(self);
};
Then back in your View -
(Note: You will need to reference the knockout.js script in your View)
<div data-bind="visible: !uploadCompleted() && uploadStarted()">
// your gif image reference will go here
// it will only be displayed when uploadCompleted is false and uploadStarted is true
</div>
<button type="button" id="uploadButton" name="Submit">Upload</button>
<script type="text/javascript">
var viewModel = new TestViewModel();
// make an ajax call to your controller method to upload your content
// on success set your loaded property to true to hide your gif
$('#uploadButton').click(function() {
viewModel.uploadStarted(true);
$j.ajax({
type: "POST",
url: "../home/Index",
data: ko.toJSON({ file: file, resModel: model}),
contentType: "application/json",
success: function (data) {
// your controller will return your values in data
// update your viewModel properties
viewModel.itemsToDisplay(data);
viewModel.uploadCompleted(true);
viewModel.uploadStarted(false);
}
});
});
</script>
Hope that helps.
Best of luck!

Close Popup Windows MVC Controller

I have a popup window opened when clicked a link on screen, the view that has the link is _DetailsSurvey. After clicking the link pop up window opens with the content of _EditSurvey view. At the end of _EditSurvey, I have button
<input type="submit" value="Save" />
I am using Ajax option and after button click I insert a row into Survey table if the modelstate is valid.
#using (Ajax.BeginForm("SubmitSurvey", "Blog", null, new AjaxOptions
{
UpdateTargetId = "context",
InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace,
HttpMethod = "Post",
Url = "/Home/SubmitSurvey"
},
new { surveyItem = #Model }))
What i want to do is if the modelstate is valid after returning from SubmitSurvey method I want the pop up window to be closed.I use the following method to achieve this but it does not work.
Employee employee;
if (ModelState.IsValid)
{
int employeeId = surveyItem.EmployeeId;
int trainingId = surveyItem.TrainingId;
employee = _work.EmployeeRepository.GetSet().
FirstOrDefault(a => a.Id == employeeId);
var training = _work.TrainingRepository.GetSet().Where(a => a.EmployeeId == employeeId && a.Id == trainingId).ToList().ElementAt(0);
training.Survey = surveyItem.survey;
training.SurveyId = surveyItem.survey.Id;
/* _work.SurveyRepository.Add(surveyItem.survey);
_work.SurveyRepository.Save();*/
_work.TrainingRepository.UpdateAndSave(training);
_work.TrainingRepository.Save();
}
else
{
return PartialView("_EditSurvey", surveyItem);
}
return JavaScript("window.close()");
I create my popup links as follows
<tr>
<td class="view_detail_label">
Eğitim Adı
</td>
<td>
#Html.ActionLink(
training.Name.Name,
"AddSurvey",
new {
employeeId = Model.Id,
trainingId = training.Id
},
new {
#class = "addSurvey"
}
)
<div class="result" style="display:none;"></div>
</td>
</tr>
The called ajax code is as follows:
$(document).ready(function () {
$('.addSurvey').click(function () {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
context: this,
success: function (result) {
$(this).next('.result').html(result).dialog({
autoOpen: true,
title: 'Anket',
width: 500,
height: 'auto',
modal: true
});
}
});
return false;
});
});
In my pop up view I am using previously shown Ajax BeginForm and below that I have the table where user inputs values of the survey. At the end I have the submit button.
<table id="context">
<tr>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.survey.Context)
</div>
</td>
<td>
<div class="editor-field">
#Html.EditorFor(model => model.survey.Context)
#Html.ValidationMessageFor(model => model.survey.Context)
</div>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Kaydet" />
</td>
</tr>
I show validation message next to each field if there is any problem with the provided input. If the model was valid I want to do either close the popup window.
It's a very bad idea to open a popup window for many reasons I won't explain here. I spend a very long time to find a solution I could consider as perfect (for me).
In my case, I prepare the view as a partial one (without html, header and body). Just the necessary items do create my functionality in a div.
Then I request my partial view using an ajax query after what I feed a div with my partial view string and I apply the JQuery dialog method to the div for my view to be displayed as a floating dialog box and I bind the OK button to an ajax post to send data to the server.
If you want to have the unobstrusive validation to works, you must parse the form with the validator.
I invite you to have a look to my framework, everything you need is available.
https://myprettycms.codeplex.com/SourceControl/latest#461106

Ajax.BeginForm refreshing the whole page in MVC

I've been trying to add some Ajax functionality to my mvc site, however, I run into a problem regarding page refreshing. I've created an rss view on my homepage sidebar, which allows the user to select which rss feed they want to view using a drop down list. Initially I was using the html.begin form option in mvc, however, I decided it would be a cool feature to have the rss feeder refresh, rather than having the whole page refresh. I implemented the ajax.begin form, but the whole page is still refreshing.
Here is the code inside my view:
<div class="rss_feed">
<h3>RSS Feed</h3>
#using (Ajax.BeginForm("Index", "Home",
new AjaxOptions
{
HttpMethod = "post",
UpdateTargetId = "feedList"
}))
{
#Html.DropDownListFor(x => x.SelectedFeedOption, Model.FeedOptions)
<input type="submit" value="Submit" />
}
<div id="feedList">
#foreach (var feed in Model.Articles)
{
<div class="feed">
<h3>#feed.Title</h3>
<p>#feed.Body</p>
<p><i>Posted #DateTime.Now.Subtract(#feed.PublishDate).Hours hour ago</i></p>
</div>
}
</div>
</div>
When the user selects a feed type from the drop down menu, and clicks the submit button, the feed should update to the selected option.
In the _Layout view the following bundle is loaded:
#Scripts.Render("~/bundles/jquery")
Any help would be great.
I use an ajax call in jquery for this
$('#SelectedFeedOption').change(function() {
$.ajax({
url: "#(Url.Action("Action", "Controller"))",
type: "POST",
cache: false,
async: true,
data: { data: $('#SelectedFeedOption').val() },
success: function (result) {
$(".feedList").html(result);
}
});
});
Then put the contents of your feedList div in a partial view and on your controller
public PartialViewResult FeedList(string data){
Model model = (get search result);
return PartialView("_feedList", model);
}
Hopefully this helps.
Did you try initializing the InsertionMode member into the AjaxOptions object initializer?
You also have to include 'jquery.unobtrusive-ajax.js' to make Ajax.BeginForm to work as answered here
#using (Ajax.BeginForm("Index", "Home", null,
new AjaxOptions
{
HttpMethod = "post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "feedList"
});
{
#Html.DropDownListFor(x => x.SelectedFeedOption, Model.FeedOptions)
<input type="submit" value="Submit" />
}

Categories

Resources