Muhammad Usman
Muhammad Usman

Reputation: 80

Integrating AngularJs with Asp.net MVC5 (Views, Controller, ModelData)

I am new to AngularJS and INTEGRATING it with ASP.NET MVC5.

I would like to know how can i call an mvc5 View along with Model Data from AngularJS in a way that it renders respective View ALONG with mapping ModelData to (ng-Model) or (controller $scope)

-- UPDATE --

As what i do in asp.net mvc5 is i have UserController with two Edit views as follows

ASP.NET MVC5 CODE

/// ########### C# CODE ##############
public class UserController : Controller
{
    // GET: USER/Edit/5
    public ActionResult Edit(string id)
    {
        try
        {
            EntitiesModel1 context = new EntitiesModel1();
            USER objUser = context.USER.SingleOrDefault(w => w.USER_ID == Id);

            **//what this return statement does, it renders given view in browser along with ModelData which will automatically be mapped with Razor Model**
            return View("Edit_View", objUser);
        }
        catch (Exception ex)
        {
            return View("~/Views/Shared/Error.cshtml");
        }
    }

    // POST: USER/Edit/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(User argUser)
    {
        try
        {
            if (ModelState.IsValid)
            {
                long userIdToUpdate = long.Parse(TempData.Peek("UserIdToUpdate").ToString());

                EntitiesModel1 context = new EntitiesModel1();
                USER entUser = context.USER.SingleOrDefault(w => w.USER_ID == userIdToUpdate);
                entUser.FirstNames= argUser.FirstNames;
                entUser.Lastname= argUser.LastName;

                context.SaveChanges();
            }

            //what this return does is, it returns control back to index page
            return RedirectToAction("Index");
        }
        catch (Exception ex)
        {
            return View("~/Views/Shared/Error.cshtml");
        }
    }
}

/// ########### RAZOR VIEW CODE ##############
@model DRS_Web.Model.USER
@using (Html.BeginForm())
{
     @Html.AntiForgeryToken()

<div>
    <label>Update User</label>
    <div >
        First name @Html.EditorFor(model => model.FirstNames)
        Last name  @Html.EditorFor(model => model.LastName)

        <input type="submit" value="Update Record" />
    </div>
</div>

}

Now in AngularJS i ve to maintain a controller at client side aswell which is controlling the flow

ASP.NET MVC5 ANGULARJS CODE

// ########### ANGULARJS CONTROLLER ###########
<addangular.module('ngAppModule').controller('ngUserController', function ($scope, $http) {
$scope.UserModel = {};    
$scope.UserList = null;
$scope.message= '';

//GET EDIT VIEW
$scope.EditGet = function (id) {
    $http({ method: 'GET', url:'/User/Edit', data: id })
    .success(function (data, status, headers, config) {
        $scope.UserModel = data;
        // **HERE IS MY QUESTION, SINCE EDIT ACTION IN USERCONTROLLER IS RETURNING VIEW NAME ALONG WITH MODEL DATA, DATA LOADED SUCCESSFULLY VIA JSON, HOW COME VIEW BE RENDERED IN BROWSER**
    })
   .error(function (data, status, headers, config) {
       $scope.message = 'Unexpected Error while loading data!!';
   });
};

//POST EDIT VIEW
$scope.EditSubmit= function () {
    $http({ method: 'POST', url:'/User/Edit', data: $scope.UserModel })
    .success(function (data, status, headers, config) {
        $scope.message = 'Data updated successfully';
    })
   .error(function (data, status, headers, config) {
       $scope.message = 'Unexpected Error while loading data!!';
       $scope.result = "color-red";
       console.log($scope.message);
   });
};

HERE IS MY QUESTION

By calling EditGet function from AngularJS will further call EDIT Action Method in UserController, and this Action Method IS RETURNING VIEW (Edit_View) ALONG WITH MODEL DATA.

So How AngularJS Handles / Render Returned view (i.e Edit_View) in browser algon with mapping returned ModelData.

Are we going to make separate views at angular level or can we utilize views at asp.net mvc5 level

Upvotes: 1

Views: 535

Answers (1)

Win
Win

Reputation: 62301

You do not want $http GET or POST to MVC Controller. Instead, you want to use Web API Controller.

The bottom line is you want JSON returning from server-side when GET or POST is performed.

You might want to watch Matt Honeycutt's Building Strongly-typed AngularJS Apps with ASP.NET MVC 5.

How to pass info between Angular and C# ASP.NET

Updated:

If you work with Angular, you want to return JSON from MVC action method.

public ActionResult Edit(string id)
{
   ....  
   return Json(objUser);     
}

Upvotes: 2

Related Questions