banner ad
We are excited to announce that the ASP.NET Forums are moving to the new Microsoft Q&A experience. Learn more >
ASP.NET Forums/General ASP.NET/MVC/issue with update record in mvc using api

issue with update record in mvc using api[Answered] RSS

10 replies

Last post Aug 25, 2020 06:58 AM by rahulpas

ASP.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today. Learn more >
  • rahulpas rahulpas

    Member

    16 Points

    112 Posts

    Re: issue with update record in mvc using api

    Aug 24, 2020 10:10 AM|rahulpas|LINK

    Hello YihuiSun

    I am not able to get the data when click on below edit button

    when I click above edit button then not able to get the data

    empsController.cs

           //here I am successfully post the data 
            [HttpPost]
            public async Task<JsonResult> Edit(mvcempmodel test)
            {
                var client = new HttpClient();
                string url = "https://localhost:44358/api/emps/checkEdit?empid=" + test.empid + "&username=" + test.username + "&empaddress=" + test.empaddress + "&password=" + test.password + "&country=" + test.country;
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = await client.GetAsync(url);
                dynamic data = null;
                if (response.IsSuccessStatusCode)
                {
                    var returnuserdata = await response.Content.ReadAsStringAsync();
                    var userdata = JsonConvert.DeserializeObject(returnuserdata);
                    if (userdata != null)
                    {
                        data = new
                        {
                            message = "Update Successfully",
                            data = test
                        };
                        return Json(data, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        data = new
                        {
                            message = "Not Updated",
                        };
                        return Json(data, JsonRequestBehavior.AllowGet);
                    }
                }
                else
                {
                    data = "request failed:" + response.StatusCode;
                }
                return Json(data, JsonRequestBehavior.AllowGet);
            }
    
            //here I am facing issue not able to get data when click on edit button
            [HttpGet]
            public async Task<ActionResult> Edit(int? empid)
            {
                var currentemp = new mvcempmodel();
                var client = new HttpClient();
                string url = "https://localhost:44358/api/emps/GetempbyId?empid=" + empid;
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    currentemp = response.Content.ReadAsAsync<mvcempmodel>().Result;
                }
                return View(currentemp);
            }

    api:

    empsController.cs

            public emp GetempbyId(int empid)
            {
                var currentemp = db.emps.Where(e => e.empid == empid).FirstOrDefault();
                return currentemp;
            }
    
            [HttpGet]
            public emp checkEdit(int empid, string username, string empaddress, string password, string country)
            {
                emp editrecord = db.emps.Where(e => e.empid == empid).FirstOrDefault();
    
                editrecord.username = username;
                editrecord.empaddress = empaddress;
                editrecord.password = password;
                editrecord.country = country;
    
                db.SaveChanges();
    
                return editrecord;
            }

    index1.cshtml

     @Html.ActionLink("Edit", "Edit", new { empid = item.empid } ) |

    why I am not getting the data when click on edit button

  • YihuiSun YihuiSun

    Contributor

    3360 Points

    947 Posts

    Re: issue with update record in mvc using api

    Aug 25, 2020 03:53 AM|YihuiSun|LINK

    Hi rahulpas,

    1. You need to make a breakpoint to check whether the StatusCode is 200, which means the request is successful.If your request fails, currentemp is null.                                    
    2. About webapi routing:
      • I added a routing template to the WebApiConfig file.Therefore, I can request the GetempbyId method according to https://localhost:44307/api/emps/GetempbyId?empid=" + empid.
        •             config.Routes.MapHttpRoute(
                         name: "customizeApi",
                         routeTemplate: "api/{controller}/{action}/{id}",
                         defaults: new { id = RouteParameter.Optional }
                     );
      • Web API will select the controller and action after finding a matching route.After finding the controller, in order to find the action, Web API first looks at the HTTP verb, and then looks for the action whose name starts with the name of the HTTP verb. But this convention only applies to verbs GET, POST, PUT, DELETE, HEAD, OPTIONS and PATCH.
        • In other words, if you only have the default route, your action name should start with Get like "GetempbyId", and your url should be "https://localhost:44307/api/emps?empid=" + empid; . At the same time, GetempbyId needs to specify the allowed HTTP verb as "HttpGet".
        • The default route created by the Web API Visual Studio project template is as follows.
          •             config.Routes.MapHttpRoute(
                            name: "DefaultApi",
                            routeTemplate: "api/{controller}/{id}",
                            defaults: new { id = RouteParameter.Optional }
                        );
    3. Regarding the routing links in webapi, you can refer to them.

    Best Regards,

    YihuiSun

    ASP.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today. Learn more >
  • rahulpas rahulpas

    Member

    16 Points

    112 Posts

    Re: issue with update record in mvc using api

    Aug 25, 2020 04:58 AM|rahulpas|LINK

    hello YihuiSun

    In webapi Controller project work fine see below image

    webapiconfig.cs

        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                config.MapHttpAttributeRoutes();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{action}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }

    when I write this url in browser

    https://localhost:44358/api/emps/GetempbyId?empid=1

    and then debugger come here this method that is ok

            public emp GetempbyId(int empid)
            {
                var currentemp = db.emps.Where(e => e.empid == empid).FirstOrDefault();
                return currentemp;
            }

    work fine 

    but issue is

    when I run my mvc project then give an error:

    RouteConfig.cs

    namespace Mvc
    {
        public class RouteConfig
        {
            public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
                routes.MapRoute(
                    name: "Default",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "emps", action = "Index1", id = UrlParameter.Optional }
                );
            }
        }
    }

    empsController.cs

            public ActionResult Index1()
            {
                ServicePointManager.ServerCertificateValidationCallback = new
            RemoteCertificateValidationCallback
            (
            delegate { return true; }
            );
    
                IEnumerable<mvcempmodel> empList;
                HttpResponseMessage response = globalvariable.webapiclient.GetAsync("emps").Result;
                empList = response.Content.ReadAsAsync<IEnumerable<mvcempmodel>>().Result;
                //return View(empList);
                return View(empList);
            }

  • YihuiSun YihuiSun

    Contributor

    3360 Points

    947 Posts

    Re: issue with update record in mvc using api

    Aug 25, 2020 05:55 AM|YihuiSun|LINK

    Hi rahulpas,

    rahulpas

    when I run my mvc project then give an error:

    1. It seems that globalvariable is a method you customize. According to the error message, it is an error caused by the code in globalvariable.
      I created a method called globalvariable.If the "/" is missing at the end of BaseAddress, I can get the same error as you. You can check your BaseAddress. If possible, you can give the relevant code of globalvariable so that we can better help you.
      •     public static class globalvariable
            {
                public static HttpClient webapiclient = new HttpClient();
                static globalvariable()
                {
                    webapiclient.BaseAddress= new Uri("https://localhost:44307/api/");
                }
            }
    2. In addition, have the problems you encountered before have been solved? Did you make a breakpoint in Edit to check if currentemp has a value.

    Best Regards,

    YihuiSun

    ASP.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today. Learn more >
  • rahulpas rahulpas

    Member

    16 Points

    112 Posts

    Re: issue with update record in mvc using api

    Aug 25, 2020 06:10 AM|rahulpas|LINK

    I change as you said but not solved error

    see all my change code:

    globalvariable.cs

    namespace Mvc
    {
        public static class globalvariable
        {
            public static HttpClient webapiclient = new HttpClient();
    
            static globalvariable()
            {
                webapiclient.BaseAddress = new Uri("https://localhost:44358/api/");
                webapiclient.DefaultRequestHeaders.Clear();
                webapiclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            }
        }
    }

    routeconfig.cs

    namespace Mvc
    {
        public class RouteConfig
        {
            public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
                routes.MapRoute(
                    name: "Default",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "emps", action = "Index1", id = UrlParameter.Optional }
                );
            }
        }
    }

    empsController.cs

            public ActionResult Index1()
            {
                ServicePointManager.ServerCertificateValidationCallback = new
            RemoteCertificateValidationCallback
            (
            delegate { return true; }
            );
    
                IEnumerable<mvcempmodel> empList;
                HttpResponseMessage response = globalvariable.webapiclient.GetAsync("emps").Result;
                empList = response.Content.ReadAsAsync<IEnumerable<mvcempmodel>>().Result;
               
                return View(empList);
            }

    Index1.cshtml

    @model IEnumerable<Mvc.Models.mvcempmodel>
    
    @{
        ViewBag.Title = "Index1";
    }
    
    <h2>ListOfRecord</h2>
    
    <p>
        @Html.ActionLink("Create Record", "Create")
    </p>
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.username)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.empaddress)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.password)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.country)
            </th>
            <th>Actions</th>
        </tr>
    
    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.username)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.empaddress)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.password)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.country)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { empid = item.empid } ) 
            </td>
        </tr>
    }
    
    </table>
    

    Did you make a breakpoint in Edit to check if currentemp has a value. ->yes

    see my above reply image and see watch window

    please help how to solve this error which place I am doing wrong

    I am trying to play with this api 

    https://localhost:44358/api/emps/getemps  //this api give the list of record and this api work fine

  • rahulpas rahulpas

    Member

    16 Points

    112 Posts

    Re: issue with update record in mvc using api

    Aug 25, 2020 06:49 AM|rahulpas|LINK

    can you paste here your index1 method code please

  • rahulpas rahulpas

    Member

    16 Points

    112 Posts

    Re: issue with update record in mvc using api

    Aug 25, 2020 06:58 AM|rahulpas|LINK

    Hello yihuisun

    issue is solved thanks you

  • ‹ Previous Thread|Next Thread ›