Showing posts with label MVC Examples. Show all posts
Showing posts with label MVC Examples. Show all posts

Wednesday, 27 July 2016

How to call web api using Ajax call

 <script>
        $(document).ready(function () {
            $("#Save").click(function () {

                var person = new Object();
                person.name = $('#name').val();
                person.surname = $('#surname').val();

                $.ajax({
                    url: 'http://localhost:11023/api/values/Get',
                    type: 'POST',
                    dataType: 'json',
                    data: person,
                    success: function (data, textStatus, xhr) {
                        console.log(data);
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        console.log('Error in Operation');
                    }
                });


            });
        });
    </script>

 Name :- <input type="text" name="name" id="name" />
        Surname:- <input type="text" name="surname" id="surname" />
        <input type="button" id="Save" value="Save Data" />



public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

Monday, 29 June 2015

Uploading files with Asp.net MVC

Uploading a single File:
Start with view having a form that will postback to the current action

<form action="" method="post" enctype="multipart/form-data">
  <label for="file">Filename:</label>
  <input type="file" name="file1" id="file1" />
  <input type="submit" />
</form>
 
In Controller
 
[HttpPost]
public ActionResult Index(HttpPostedFileBase file1) {

  if (file1.ContentLength > 0) {
    var fileName = Path.GetFileName(file1.FileName);
    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
    file1.SaveAs(path);
  }

  return RedirectToAction("Index");
} 


"~/App_Data/uploads" is a folder to upload files on server.
 
Uploading multiple files: 

In view 

<form action="" method="post" enctype="multipart/form-data">
  <label for="file1">File name:</label>
  <input type="file" name="files1" id="file1" />
  <label for="file2">File name:</label>
  <input type="file" name="files1" id="file2" />
  <input type="submit"  />
</form>
 
In Controller:
 
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files) {
  foreach (var file1 in files) {
    if (file1.ContentLength > 0) {
      var fileName = Path.GetFileName(file1.FileName);
      var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
      file1.SaveAs(path);
    }
  }
  return RedirectToAction("Index");
} 
Here we are getting list of files so we are using IEnumerable to list the files.
So you can upload multiples files on server.