Menu
  • HOME
  • TAGS

How to Upload file onclick of button of type=button not type=submit in mvc4 using html begin form

Tag: file,asp.net-mvc-4,button,upload,submit

I have to upload a file using a button (of type button, not submit).

And I want to show popup when no-file is selected and clicked on upload, it should not go to controller action.

Can anyone help please?

Best How To :

@using(Html.BeginForm("Upload","Home",new {@id="frm"}))
{
    <input type="file" id="upld" />
    <input type="button" value="upload" id="btn" />
}

<script>
  $('#btn').click(function(){
     var has_selected_file = $('#upld').filter(function(){
          return $.trim(this.value) != ''
     }).length  > 0 ; 
     if(has_selected_file){
          $('#frm').submit();
      }
      else{
          alert('No file selected');
      }
  });

I hope this is your requirement

C# Using Bool, how to check a double is truly divisible by another number? [duplicate]

c#,asp.net-mvc-4

You can use the %-operator: bool isDivisible = 1115 % 100 == 0; The % operator computes the remainder after dividing its first operand by its second. All numeric types have predefined remainder operators. ...

Why mozilla changes the characters when i use the .net mvc statement redirect?

c#,asp.net-mvc-4,redirect,mozilla

%E2%80%8B is a URL-encoded, UTF-8 encoded ZERO-WIDTH SPACE character. You likely have one hiding in your application setting file for the ProActiveOffice-URL value. It was maybe pasted in that way, if you copied the URL from somewhere.

Storing columns on disk and reading rows

c++,file,matrix,io

Mentioned solution with fseek is good. However, it can be very slow for large matrices (as disks don't like random access, especially very far away). To speed up things, you should use blocking. I'll show a basic concept, and can explain it further if you need. First, you split your...

How to get rid of .ignore file in Git?

git,file,bitbucket,ignore

.gitignore is just like any other file under version control, so yes, you can delete it. However, keep in mind that it probably has entries in it that should be kept, so instead of deleting it, I would just modify it so that your jar files are no longer ignored.

How to Implement Dependent Dropdownlist in MVC4 Razor and using SQL server also

sql-server,asp.net-mvc-4,razor

Note : As per your requirement you need to show country name when user selects the state then why you need dropdownlist for country ?? it is better to use a label for that. For you requirement first you have to maintain a table which stores country and it's state...

Mvc Remote Attribute is sending “undefined” in query string

c#,asp.net,asp.net-mvc,asp.net-mvc-4

You need to add @Html.HiddenFor(m=>m.UserId) at the view so that the binder will bind it to the remote validation controller or otherwise there is no value to bind ...

MVC Push notification from server to client side

asp.net-mvc-4,push-notification

You can use SignalR : $.connection.hub.start().done(function () { $('#sendmessage').click(function () { // Call the Send method on the hub. chat.server.send($('#displayname').val(), $('#message').val()); // Clear text box and reset focus for next comment. $('#message').val('').focus(); }); }); use more info: tutorial...

How to get started with Visual studio 2012

c#,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-4,visual-studio-2012

Download this book "Microsoft ASP.NET 4 Step By Step" by George Shepherd.I found it very helpful.It will address all the issues you raised here.Thank you.

Changing file name to the user's name PHP

php,file,upload

You need to change your $target_file variable to the name you want, since this is what gets passed into move_uploaded_file(). I don't see anywhere in your code where you actually set this variable to their username (right now it's still using the name they selected when they uploaded it). Without...

Python - Select specific value from test file

python,file,text

You could split the text and have a list of lists, where each sub list is a row, then pluck whatever you need from the list using rows[row - 1][column - 1]. f = open('test.txt', 'r') lines = f.readlines() f.close() rows = [] for line in lines: rows.append(line.split(' ')) print...

C# entity framework MVC second run error

entity-framework,asp.net-mvc-4,localdb

Your initialiser is using the DropCreateDatabaseAlways class which, as it suggests, drops that database every time the application is initialised. Instead perhaps you could use CreateDatabaseIfNotExists or DropCreateDatabaseIfModelChanges: public class ComponentDbInitialize : CreateDatabaseIfNotExists<ComputerContext> { } ...

C++ reading and editing files

c++,file

This is the start of what you want. Because this is an assignment I have left you with some reading, and the remainder of the assignment. I have also translated much of the code to read in Portuguese. #include <iostream> #include <fstream> // seu códe // Faça isso para ler...

Rust: Lifetime of String from file [duplicate]

file,io,rust

The string bound to "s" will be deallocated once the function ends ("s" goes out of scope), so you cannot return a reference to its contents outside the function. The best way is to return the string itself: fn read_shader_code(string_path: &str) -> String { let path = Path::new(string_path); let display...

Display value of a textbox inside another textbox using AngularJs on button click

angularjs,asp.net-mvc-4

in your controller do , $scope.myFunction = function () { $scope.display = $scope.type; } in your html you have to change onclick to ng-click, <input type="button" value="button" ng-click="myFunction()" /> see this plunk for example, http://plnkr.co/edit/c5Ho1jlixwZFx7pLFm9D?p=preview...

Setting up routing when RemoteAttribute specifies AdditionalFields

c#,asp.net,asp.net-mvc,asp.net-mvc-4

When it receives a query such as /Validation/IsUserNameAvailable?userName=BOB&UserID=, MVC's model binder is confused because it does not know how to handle null/empty string params. Just change the param to an int and cast as necessary for your helper method: public JsonResult IsUserNameAvailable(string userName, int UserId) { var users = new...

Reading a text file with Tabs

c#,asp.net,.net,file,readfile

There's no tab entity defined in ISO-8859-1 HTML, so I think you can replace tab characters with some &nbsp; characters: if (File.Exists(path)) { using (TextReader tr = new StreamReader(path)) { while (tr.Peek() != -1) { var htmlLine = tr.ReadLine().Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;") + "<br/>"; Response.Write(htmlLine); } } } ...

Storing multiple columns of data from a file in a variable

bash,file

Example code: #!/bin/bash declare -a textarr numarr while read -r text num;do textarr+=("$text") numarr+=("$num") done <file echo ${textarr[1]} ${numarr[1]} #will print Toy 85 data are stored into two array variables: textarr numarr. You can access each one of them using index ${textarr[$index]} or all of them at once with ${textarr[@]}...

Getting HTTP 302 when downloading file in Java using Apache Commons

java,file,url,apache-commons,fileutils

The code 302 refers to a relocation. The correct url will be transmitted in the location header. Your browser then fetches the file form there. See https://en.wikipedia.org/wiki/HTTP_302 Try https://repo1.maven.org/maven2/com/cedarsoftware/json-io/4.0.0/json-io-4.0.0.jar For FileUtils see How to use FileUtils IO correctly?...

How to upload file in PHP and store information in SQLi database?

php,file,mysqli,upload

I see you have called the bindParameters() method after calling execute(). It should be the other way round. i.e. $stmt->bind_param('ssis',$complete,$file_name,$fileSize,$myUrl); $stmt->execute(); ......

How to add validators for @Html.TextBox() without model

asp.net-mvc,asp.net-mvc-4

Add data-val and data-val-required attribute for Html.TextBox() as shown below. <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> @using (Html.BeginForm("","")) { @Html.ValidationSummary() @Html.TextBox("bill_address", null, new { @class = "form-control valid", @data_val = "true", @data_val_required = "Billing Address is required" }) <input type="submit" value="Click"...

Angularjs ng-show doesn't work with Viewbag

angularjs,asp.net-mvc-4

Try this: <div ng-show="'@(ViewBag.AllowExport)'"> <a href="JavaScript:void(0);">Export</a> </div> ...

check for value null on razor syntax

c#,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-4,razor

try this: @{ if (propiedadesFormularioDetalle != null) { <div class="panel panel-default"> <div class="panel-heading">Propiedades adicionales</div> <div class="panel-body"> <dl class="dl-horizontal"> foreach (KeyValuePair<string, string> propiedad in propiedadesFormularioDetalle) { <dt> Html.DisplayName(propiedad.Key) </dt> <dd> Html.DisplayFor(prop => propiedad.Value) </dd> } </dl> </div> } </div> } ...

ValueError: dictionary update sequence element #0 has length 1; 2 is required while reading from file

python,file,dictionary

dict() does not parse Python dictionary literal syntax; it won't take a string and interpret its contents. It can only take another dictionary or a sequence of key-value pairs, your line doesn't match those criteria. You'll need to use the ast.literal_eval() function instead here: from ast import literal_eval if line.startswith(self.kind):...

Cannot get data using LINQ in MVC

c#,asp.net-mvc,linq,asp.net-mvc-4

Ensure term matches the case of the data. As all the data is loaded (.ToList() in the DAL), the .Where clause uses .Net comparison rather than SQL comparison: var vehicle = _service.GetAll().Where(c => c.Name.StartsWith(term, StringComparison.OrdinalIgnoreCase)... If, in the future, you want to change this to Contains, you can add an...

IllegalStateException: Iterator already obtained [duplicate]

java,file,loops,path

You have to call DirectoryStream<Path> files = Files.newDirectoryStream(dir); each time you iterate over the files. Pls check this question... java.lang.IllegalStateException: Iterator already obtained...

Use “Contains” to match part of string in lambda expression

c#,jquery,asp.net-mvc-4,lambda

I would search your initial items (before you made the into a list of TextValuePair) then you could do something like IEnumerable<Item> items = originalItemsList; switch (source) { case "1": // or whatever this should be items = items.Where(x => x.ItemNumber.IndexOf(data, StringComparison.InvariantCultureIgnoreCase) > -1); break; case "2": // or whatever...

C# mvc4 - direct URL to controller

c#,asp.net-mvc-4,url,redirect

You might have forgotten to specify name of the controller in Html.ActionLink() parameter. Try Html.ActionLink("actionname","controllername");

Check if file exists using Apache Commons VFS2

java,file,sftp,apache-commons-vfs

Use FileObject.exists() method. See https://commons.apache.org/proper/commons-vfs/apidocs/org/apache/commons/vfs2/FileObject.html#exists%28%29...

How to make new line when using echo to write a file in C

c,linux,file,echo,system

There is one new line, which is to be expected. The echo command prints all its arguments on a single line separated by spaces, which is the output you see. You need to execute the result of: echo "$(ls %s)" to preserve the newlines in the ls output. See Capturing...

Conflicted with the REFERENCE constraint. How to solve this?

asp.net-mvc-4,nhibernate

Judging by that error, your repository is trying to delete the a user from its table but that user is referenced in another table (dbo.Invoices). So you are seeing a foreign key constraint error where you are trying to delete a record who's primary key is referenced in another table...

Realm.io Removing the realm file

ios,file,realm

That is the proper way of deleting it. You can check the Migration example in the RealmExample project that come with the SDK and see that that's exactly how they do it, so I assume the recommended way. let defaultPath = Realm.defaultPath NSFileManager.defaultManager().removeItemAtPath(defaultPath, error: nil) ...

Unable to make parent li active on click of child li with bootstrap in mvc4

c#,asp.net,asp.net-mvc-4,c#-4.0

There are 2 things to do, one is make the active selection when user clicks and the other is save this selection after the page refreshs right? If you want to make li selected after the page refresh you need to save this state somewhere. You can save it in...

How to test existence of 'file' that cannot be accessed?

c,file

Since the next thing we plan to do is create something at that location, and since we want to treat it as an error if something already exists there, then let's not bother checking. Just attempt the create and exit with an error if it fails. The create step uses...

Strings vs binary for storing variables inside the file format

c++,file,hdf5,dataformat

Speaking as someone who's had to do exactly what you're talking about a number of time, rr got it basically right, but I would change the emphasis a little. For file versioning, text is basically the winner. Since you're using an hdf5 library, I assume both serializing and parsing are...

Delphi - Use a string variable's name in assignfile()

file,delphi,variables,assign

Is it possible to use a variable in the AssignFile command? Yes. The second parameter of AssignFile has type string. The expression cFileDir + '\' + sFile has type string. FWIW, AssignFile is known as a function rather than a command. Getting on top of terminology like this will...

Saying there are 0 arguments when I have 2? Trying to open a CSV file to write into

ruby,file,csv,dir

I believe the problem is with Dir.foreach, not CSV.open. You need to supply a directory to foreach as an argument. That's why you are getting the missing argument error. Try: Dir.foreach('/path/to_my/directory') do |current_file| I think the open that is referenced in the error message is when Dir is trying to...

Dynamically adding controls in MVC4

asp.net-mvc,asp.net-mvc-4

You can create a editor template and pass the control list as model to the template and in the template you can iterate that list to generate the control. As i have shown below. 1->Create a class for Control Information. public class ControlInfo { public string ControlType { get; set;...

Why is my linked list only printing last entry?

c,file,linked-list

The problem is the way you are treating the result of strtok: you are setting its value right into the node, instead of copying it. Make a copy of name when adding a node: void push(node ** head, int uid ,char* uname) { node * new_node; new_node = malloc(sizeof(node)); new_node->uid...

How to store a string in xml file and use it in _Layout in MVC

c#,xml,asp.net-mvc,asp.net-mvc-4

Sourced: from this link The web.config (or app.config) is a great place to store custom strings: in web.config: <appSettings> <add key="message" value="Hello, World!" /> </appSettings> in cs: string str = ConfigurationSettings.AppSettings["message"].toString(); ...

How to know fast if another computer is accesible in AS3 (Adobe Air)

file,actionscript-3,air,lan

While I don't know of a method to make File.exists() perform faster (likely there is no way as it's more of an OS issue), you can at least mitigate the issue by using asynchronous operations instead - thus avoiding locking the UI. You can skip the exists operation, and just...

How do I let the user name the output.txt file in my C program?

c,file

You can read the input from user and append .txt char fileName[30]; // ... scanf("%25s", fileName); // max 25 characters because .txt have 4 (25+4 = 29) strcat(fileName, ".txt"); // append .txt extension // ... FILE *f = fopen(fileName, "a"); ...

How to Write to a Certain Line in a File in VB

vb.net,file,file-access

I don't know if you can write to a specific line in a file, but if you need to you can write your lines to a List then write the list to a file 'Declare your list Dim lines As New List(Of String) For Each lineToWrite In YourLines If toInsert...

Use Bearer Token Authentication for API and OpenId authentication for MVC on the same application project

c#,asp.net-mvc-4,oauth-2.0,openid,identityserver3

Ok, I found some information on the following post https://github.com/IdentityServer/IdentityServer3/issues/487 The github repo that implements the concepts discussed in the link can be found here https://github.com/B3nCr/IdentityServer-Sample/blob/master/B3nCr.Communication/Startup.cs Basically you need to map the api url to a different configuration using app.Map(). In my case, I changed my startup file to look...

File not Uploading using Ajax in cakephp

php,jquery,ajax,file,cakephp

With this AJAX form submission approach, you will not be able to upload file using ajax. If you don't like using a third-party plugin like dropzone.js or Jquery file upload, you can use XMLHttpRequest. An example below: $('#newcatform').on('submit', function(ev){ ev.preventDefault(); var forms = document.querySelector('form#newcatform'); var request = new XMLHttpRequest(); var...

Group instances based on NA values in r

r,file,csv,instance,na

df[!is.na(df$Value), ] Size Value Location Num1 Num2 Rent 1 800 900 <NA> 2 2 y 3 1100 1300 uptown 3 3 n 4 1200 1100 <NA> 2 1 y And df[is.na(df$Value), ] Size Value Location Num1 Num2 Rent 2 850 NA midcity NA 3 y 5 1000 NA Lakeview NA...

Why is my View not displaying value of ViewBag?

c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor

ViewBag is used when returning a view, not when redirecting to another action. Basically it doesn't persist across separate requests. Try using TempData instead: TempData["Tag"] = post.SelectedTag.ToString(); and in the view: <p><strong>Tag: @TempData["Tag"]</strong></p> ...

Add XElement dynamically using loop in MVC 4?

c#,xml,asp.net-mvc-4,for-loop

This is the complete code [HttpPost] public ActionResult SURV_Answer_Submit(List<AnswerQuestionViewModel> viewmodel, int Survey_ID, string Language) { if (ModelState.IsValid) { var query = from r in db.SURV_Question_Ext_Model.ToList() join s in db.SURV_Question_Model on r.Qext_Question_ID equals s.Question_ID where s.Question_Survey_ID == Survey_ID && r.Qext_Language == Language orderby s.Question_Position ascending select new { r, s };...

MVC 5 OWIN login with claims and AntiforgeryToken. Do I miss a ClaimsIdentity provider?

asp.net-mvc,asp.net-mvc-4,razor,asp.net-mvc-5,claims-based-identity

Your claim identity does not have ClaimTypes.NameIdentifier, you should add more into claim array: var claims = new List<Claim> { new Claim(ClaimTypes.Name, "Brock"), new Claim(ClaimTypes.Email, "[email protected]"), new Claim(ClaimTypes.NameIdentifier, "userId"), //should be userid }; To map the information to Claim for more corrective: ClaimTypes.Name => map to username ClaimTypes.NameIdentifier => map...

Python3 create files from dictionary

file,python-3.x,dictionary

Remove the if not len(key) != len(aDict) and the break. What you probably wanted to do is stopping the loop after iterating all the keys. However key is one of 'OG_1', 'OG_2', 'OG_XX', it's not a counter or something like that. Replace open("key", "w") with open(key + ".txt", "w")....

Binding my view model to a view causes all check boxes to be checked

c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor

In your view, remove <input type="checkbox" value="" checked="checked"/> Allow Access Because of checked="checked", this will always print out a checked checkbox....