2

I have created an ASP.NET MVC project to perform CRUD operations from list instead of using database, using HomeController and an API controller. Now I want to edit that project such a way that I want to call API functions directly from my view which is an HTML page.

The control is passing from view to home controller then to API controller. I want a direct connection between view and API using jQuery and AJAX.

What all further details should I specify with the question?

<script>
            $(document).ready(function () {
                    $('#login').click(function () {
                     var x = $('#email1').val()
                     var y = $('#pswd').val()
 
                     $.ajax({
                         type: "GET",
                         url: "https://localhost:44347/api/Values/Login/" + x+y,
                         contentType: "application/json; charset=utf-8",
                         dataType: "json",
                         success: function (data) {
                             window.location.replace("Studentdataproject\Studentdataproject\Views\Home\Details.cshtml");
                             },
                         error: function (data) {
                             alert(data.responseText);
                         }
                 });
                     });   }

This is the script that I had in login view to call login in API controller. It is not calling the API controller.

API for login:

[HttpGet("Login/{email}/{password}")]
        public async System.Threading.Tasks.Task<IActionResult> LoginAsync(string email, string password)
        {
            obj1 = obj2.Login(email, password);
            if (obj1 == null)
            {
                return Ok(null);
            }
            else
            {
                var claims = new List<Claim>()
                {
                    new Claim(ClaimTypes.Name,obj1.email),
                    new Claim(ClaimTypes.Role,obj1.roles)
                };
                var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                var princilple = new ClaimsPrincipal(identity);
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, princilple);

                return Ok();
            }
        }
4
  • What have you done so far? Seems like you already know what to do. You can use ajax to call for your api directly. Commented Feb 26, 2020 at 6:38
  • @javachipper i had mentioned the script that i tried, to call api from my html login page but its not working Commented Feb 26, 2020 at 9:26
  • Can you also post your web api, atleast the login function? That would help me determine if your url is correct or not. Commented Feb 26, 2020 at 10:06
  • @javachipper i mentioned it in the question Commented Feb 26, 2020 at 10:28

1 Answer 1

5

You need to change your URL in AJAX like this:

url: "https://localhost:44347/api/Values/Login/" + x + "/" + y,

Call web API with AJAX, which is similar to calling controller method.

Here is the CRUD operation of the People class with AJAX calling API. You can refer to it.

People Class:

 public class People
{ 
    [Key]
    public int id { get; set; }

    public string name { get; set; }
}

Api:

[Route("api/[controller]")]
[ApiController]
public class APICRUDController : ControllerBase
{
    private readonly MydbContext _context;

    public APICRUDController(MydbContext context)
    {
        _context = context;
    }
    [HttpGet("GetPerson")]
    public IActionResult GetPerson(int? id)
    {
        var person = _context.People.ToList();
        if (id != null)
        {
            person = person.Where(x => x.id == id).ToList();
        }
        return Ok(person);
    }

    [HttpPost("AddPerson")]
    public IActionResult AddPerson([FromBody]People obj)
    {
        if (!ModelState.IsValid)
        {
            return Ok("Please enter correct fields!");
        }
        _context.People.Add(obj);
        _context.SaveChanges();
        return Ok("Person added successfully!");
    }

    [HttpPost("UpdatePerson")]
    public IActionResult UpdatePerson([FromBody]People obj)
    {
        People people = (from c in _context.People
                         where c.id == obj.id
                         select c).FirstOrDefault();
        people.name = obj.name;
        _context.SaveChanges();
        return Ok();
    }

    [HttpPost("DeletePerson")]
    public void DeletePerson(int Id)
    {
        People people = (from c in _context.People
                             where c.id == Id
                             select c).FirstOrDefault();
        _context.People.Remove(people);
        _context.SaveChanges();
    }
}

View code:

@model WebApplication_core.Models.People
@{
    ViewData["Title"] = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@section Scripts{
    <script>
        $(function () {
            loadData();
        })
        function loadData() {
            $.ajax({
                url: 'https://localhost:44361/api/APICRUD/GetPerson',
                type: "GET",
                dataType: "json",
                success: function (result) {
                    var html = '';
                    $.each(result, function (key, item) {
                        html += '<tr>';
                        html += '<td>' + item.id + '</td>';
                        html += '<td>' + item.name + '</td>';
                        html += '<td><a href="#" onclick="return Edit(' + item.id + ')">Edit</a> | <a href="#" onclick="Delete(' + item.id + ')">Delete</a></td>';
                        html += '</tr>';
                    });
                    $('.tbody').html(html);
                },
                error: function (errormessage) {
                    alert(errormessage.responseText);
                }
            });
        }
        function Add() {
            var obj = {
                name: $('#name').val(),
            };
            $.ajax({
                type: "POST",
                url: 'https://localhost:44361/api/APICRUD/AddPerson',
                contentType: "application/json;charset=utf-8",
                data: JSON.stringify(obj),
                success: function (result) {
                    if (result.indexOf("successfully") > -1) {
                        loadData();
                        $('#myModal').modal('hide');
                        $('#name').val("");
                    }
                    alert(result);
                },
                error: function (errormessage) {
                    alert(errormessage.responseText);
                }
            });
        }
        function Edit(Id) {
            $("#myModalLabel").text("Edit Person");
            $("#id").parent().show();
            $('#name').css('border-color', 'lightgrey');
            $.ajax({
                url: 'https://localhost:44361/api/APICRUD/GetPerson?id=' + Id,
                typr: "GET",
                contentType: "application/json;charset=UTF-8",
                dataType: "json",
                success: function (result) {
                    if (result.length > 0) {
                        $('#id').val(result[0].id);
                        $('#name').val(result[0].name);
                        $('#myModal').modal('show');
                        $('#btnUpdate').show();
                        $('#btnAdd').hide();
                    }
                },
                error: function (errormessage) {
                    alert(errormessage.responseText);
                }
            });
            return false;
        }
        function Update() {
            var obj = {
                id: parseInt($('#id').val()),
                name: $('#name').val(),
            };
            $.ajax({
                url: 'https://localhost:44361/api/APICRUD/UpdatePerson',
                data: JSON.stringify(obj),
                type: "POST",
                contentType: "application/json;charset=utf-8",
                success: function () {
                    loadData();
                    $('#myModal').modal('hide');
                    $('#id').val("");
                    $('#name').val("");
                },
                error: function (errormessage) {
                    alert(errormessage.responseText);
                }
            });
        }
        function Delete(Id) {
            if (confirm("Are you sure you want to delete this Record?")) {
                $.ajax({
                    url: 'https://localhost:44361/api/APICRUD/DeletePerson?Id=' + Id,
                    type: "POST",
                    contentType: "application/json;charset=UTF-8",
                    success: function () {
                        alert("delete successfully!");
                        loadData();
                    },
                    error: function (errormessage) {
                        alert(errormessage.responseText);
                    }
                });
            }
        }
        function HideKey() {
            $("#myModalLabel").text("Add Person");
            $("#id").parent().hide();
        }


    </script>
}


<div class="container">
    <h2>People Record</h2>
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" onclick="HideKey()">Add New User</button><br /><br />
    <table class="table table-bordered table-hover">
        <thead>
            <tr>
                <th>
                    ID
                </th>
                <th>
                    Name
                </th>
                <th>
                    Action
                </th>
            </tr>
        </thead>
        <tbody class="tbody"></tbody>
    </table>
</div>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h4 class="modal-title" id="myModalLabel"></h4>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <label asp-for="id"></label>
                        <input asp-for="id" class="form-control" disabled />
                    </div>
                    <div class="form-group">
                        <label asp-for="name"></label>
                        <input asp-for="name" class="form-control" />
                        <span class="field-validation-valid text-danger" asp-validation-for="name"></span>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="btnAdd" onclick="return Add();">Add</button>
                <button type="button" class="btn btn-primary" id="btnUpdate" style="display:none;" onclick="Update();">Update</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

Here is the result of this demo:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

thank you ! now my login call to api is working fine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.