RenderPartialViewToString / Return multiple partial views in JSON - MVC6

by Admin 5. May 2016 00:00

I got a situation where we need to dynamically render multiple partial views and bid on the view in MVC6

So Here is the solution.

This is the common method for rendering the partial views as strings

protected string RenderPartialViewToString(string viewName, object model)

        {

            if (string.IsNullOrEmpty(viewName))

                viewName = ActionContext.ActionDescriptor.Name;

 

            ViewData.Model = model;

 

            using (var sw = new StringWriter())

            {

                var engine = Resolver.GetService(typeof(ICompositeViewEngine))

                    as ICompositeViewEngine;

                var viewResult = engine.FindPartialView(ActionContext, viewName);

 

                var viewContext = new ViewContext(

                    ActionContext,

                    viewResult.View,

                    ViewData,

                    TempData,

                    sw,

                    new HtmlHelperOptions()

                );

                //Everything is async now!

                var t = viewResult.View.RenderAsync(viewContext);

                t.Wait();

                return sw.GetStringBuilder().ToString();

            }

        }

 

Here is the method for the view which returns multiple partial view results as JSON

public async Task<ActionResult> GetMultiplePartialsAsync(Your input parameters go here)

        {

            var viewModel = await _myService.FetchDatasAsync(Your input parameters go here);

   //For brevity I am assigning the same view model to all the partial views.

   //You can have sub models in the view model too

                var json = Json(new

                {

                    FilterPartialViewHtml = RenderPartialViewToString("PagedResults", viewModel),

                    CountriesPartialViewHtml = RenderPartialViewToString("Countries", viewModel),

                    NamesPartialViewHtml = RenderPartialViewToString("Names", viewModel)

                });

                return json;

 

        }

 

Here is my View which load all the 3 partial views on load & on click of a checkbox

Note that the paritals are loaded on load as well as gets reladed on all onchange events of the checkbox for countries & Names

@model ResultViewModel

@{

    Layout = "~/Views/Shared/_DemoLayout.cshtml";

}

<div id="wrapper">

    <main id="content" role="main">

            

            <div class="filtering">

                <div class="filter-form">

                    <div class="inner-block">

                        <form method="get" action="Filter">

                            <div class="filter text-filter">

                                <label class="legend" for="finder-keyword-search">Search</label>

                                <input value="" type="text" name="Keywords" id="Keywords" aria-controls="js-search-results-info" class="text">

                            </div>

                            <div id="divCenturies">

                            </div>

                            <div id="divLastNames">

                            </div>

                        </form>

                    </div>

                </div>

                <div class="js-live-search-results-block">

                    <div class="filtered-results">

                            <div id="searchResults">

                            </div>

                            

                    </div>

                </div>

            </div>

    </main>

</div>

<script>

    var url = '@Url.Action("GetMultiplePartialsAsync", "Search")';

 

    $(window).load(function () {

        SearchData();

        $('#searchResults').hide();

    });

 

    $(document).ready(function () {

        $('#searchResults').hide();

        $('#divCenturies').hide();

        $('#divLastNames').hide();

        $(document).on("change", "input[type=checkbox]", function () {

            SearchData();

        });

 

        $("#Keywords").change(function () {

            SearchData();

        });

        $("#Keywords").keypress(function (e) {

            if ((e.keyCode || e.which) == 13) {

                e.preventDefault();

                SearchData();

            }

        });

    });

 

    function SearchData() {

        $.get(url, { Your input parameters here },

                function (data) {

                    $("#searchResults").html(data.FilterPartialViewHtml);

                    $("#divCenturies").html(data.CountriesPartialViewHtml);

                    $("#divLastNames").html(data.NamesPartialViewHtml);

                });

        $('#searchResults').show();

        $('#divCenturies').show();

        $('#divLastNames').show();

    }

</script>

 

Tags:

.NET core features

by Admin 7. April 2016 02:26

 

.NET core

DNX – Dot Net Execution Environment

Native process for hosting the CLR (dnx.exe)

Includes compiler and xpat tools for building .NET apps

Xpat/ OSS friendly project system (project.json)

Package based (install, restore, pack)

Side by side versioning (Manage DNX’s with the .Net Version Manager (DNVM)

Rosyln compiler  

Tags:

Autofac Dependency Injection in ASP.NET 5

by Admin 21. March 2016 11:50

A. Add the following Autofac reference in the project.json file

                        "Autofac.Extensions.DependencyInjection": "4.0.0-rc1-177"

               Note: the version number might change based on the new releases

B. Introduce the following changes in the Startup.CS file

1. Change the method return type from Void to IServiceProvider like this

                         public IServiceProvider ConfigureServices(IServiceCollection services)

2. Add the following line items after  // Add application services.

            //Autofac DI 

            var builder = new ContainerBuilder();

            //builder.RegisterModule<DataModule>();

            builder.RegisterType<TestService>().As<ITestService>().InstancePerDependency();   // This is a test class and interface I have added on to the              project.

            builder.Populate(services);

            var container = builder.Build();

            return container.Resolve<IServiceProvider>();

3. Usage is quite straight forward as in previous versions

   I have tried implementing in the HomeController.

private readonly ITestService _testService;

        public HomeController(ITestService testService)

        {

            _testService = testService;

        }

        public IActionResult Index()

        {

            ViewData["temp"] = _testService.GetTestString();

            return View();

        }

Thats it!         

 

 

Tags:

Resharper keyboard shortcuts not working in VS2015

by Admin 18. March 2016 11:00

I had an issue earlier with Resharper shortcuts not working in Visual Studio 2015.

I had to follow to use these steps to make Resharper work again

1. Tools > Options > Keyboard > Click on the Reset button (top right) and click ok.

2. Tools > Options > Resharper > Options > Click on Apply Scheme and click Save.

Now close and re-open your visual studio. Hope the Reharper shortcuts are back to life again!

Ctrl + T :)

Tags:

Git stuff

by Admin 15. March 2016 12:50


Setting Identity in GIT
$ git config --global user.name "UserName"
$ git config --global user.email "venkat@VenkatRangala.com"

To unblock the proxy

$ git config --global http.proxy "http://xx.xx.xx.xx:8080/"
$ git config --global https.proxy "http://xx.xx.xx.xx:8080/"


gitignore file creation in Windows
$ touch .gitignore


Create a Branch in GIT
$ git branch <BranchName>

To switch to the branch name
$ git checkout <BranchName>

Create Branch & checkout

git checkout -b "<BranchName>"


Add a file from command in GIT
$ touch <filename>
Eg: $ touch styles.css
A new styles.css file gets added to the git repository


$ git checkout master
Will switch you to the main branch


$ git mergetool
uses a tool like tortisegit or winmerge to perform merge a little more effeciently

 

Best way to merge a git branch into master

My work on test branch is complete and I am ready to merge it back to master

git checkout master

git pull origin master

git merge test

git push origin master

 

Useful Links

http://juristr.com/blog/2013/04/git-explained/

https://dzone.com/articles/git-visual-studio-and-net

https://visualstudiogallery.msdn.microsoft.com/abafc7d6-dcaa-40f4-8a5e-d6724bdb980c

Tags:

Publishing to an Azure Web App with Continuous Deployment

by Admin 22. January 2016 07:28

Publishing to an Azure Web App with Continuous Deployment

http://docs.asp.net/en/latest/publishing/azure-continuous-deployment.html

Tags:

Git commonly used commands

by Admin 5. April 2015 01:51

Basic Git commands

Go to the master branch to pull the latest changes from there

git checkout master

Download the latest changes in the project

This is for you to work on an up-to-date copy (it is important to do every time you work on a project), while you setup tracking branches.

git pull REMOTE NAME-OF-BRANCH -u

(REMOTE: origin) (NAME-OF-BRANCH: could be "master" or an existing branch)

Create a branch

Spaces won't be recognized, so you need to use a hyphen or underscore.

git checkout -b NAME-OF-BRANCH

Work on a branch that has already been created

git checkout NAME-OF-BRANCH

View the changes you've made

It's important to be aware of what's happening and what's the status of your changes.

git status

Add changes to commit

You'll see your changes in red when you type "git status".

git add CHANGES IN RED git commit -m "DESCRIBE THE INTENTION OF THE COMMIT"

Send changes to gitlab.com

git push REMOTE NAME-OF-BRANCH

Delete all changes in the Git repository, but leave unstaged things

git checkout .

Delete all changes in the Git repository, including untracked files

git clean -f

Merge created branch with master branch

You need to be in the created branch.

git checkout NAME-OF-BRANCH git merge master

 


Revert all local changes in Git managed project to previous state?

Here the current bash script for doing it

#!/bin/sh
git reset --hard
git clean -f -d
git checkout -- HEAD

Run from root directory of your working copy

Tags:

HTML5 validation in Angular

by Admin 4. December 2014 00:05

Angular leverages HTML5 validation attributes and new HTML5 form elements. If we want Angular to handle validation we need to first stop HTML5 to do validation.
To do this specify “novalidate” attribute on the form tag.
<form name="frm1" novalidate>
-----
-----
</form>

So now the HTML will not fire any validations, instead it will be route to the Angular engine to take actions.
In other words when end user fills data in the HTML UI , validation events are routed to Angular framework, depending on scenario Angular sets a field called as “$Valid”. So if the validations are fine it sets it to “True” or else its sets it to “False”.

Tags:

Angular Autocomplete

by Admin 28. October 2014 03:53

<div ng-app='MyModule'>
    <div ng-controller='DefaultCtrl'>
        <input auto-complete ui-items="names" ng-model="selected">
        selected = {{selected}}
    </div>
</div>

DefaultCtrl

function DefaultCtrl($scope) {
    $scope.names = ["Aiden","Jackson","Ethan","Liam","Mason","Noah","Lucas","Jacob","Jayden","Jack","Logan","Ryan","Caleb",
"Benjamin","William","Michael","Alexander","Elijah","Matthew","Dylan","James","Owen","Connor","Brayden",
"Carter","Landon","Joshua","Luke","Daniel","Gabriel","Nicholas","Nathan","Oliver"];
}

angular.module('MyModule', []).directive('autoComplete', function($timeout) {
    return function(scope, iElement, iAttrs) {
            iElement.autocomplete({
                source: scope[iAttrs.uiItems],
                select: function() {
                    $timeout(function() {
                      iElement.trigger('input');
                    }, 0);
                }
            });
    };
});

References:

 

https://material.angularjs.org/latest/demo/chips

https://ghiden.github.io/angucomplete-alt/#example1

http://ngmodules.org/modules/ngAutocomplete

Tags:

Search for a string in all the tables in SQL SERVER 2012

by Admin 14. June 2014 00:22

 

CREATE PROC SearchAllTables

(

@SearchStr nvarchar(100)

)

AS

BEGIN

 

    CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

 

    SET NOCOUNT ON

 

    DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)

    SET  @TableName = ''

    SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

 

    WHILE @TableName IS NOT NULL

 

    BEGIN

        SET @ColumnName = ''

        SET @TableName = 

        (

            SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))

            FROM     INFORMATION_SCHEMA.TABLES

            WHERE         TABLE_TYPE = 'BASE TABLE'

                AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName

                AND    OBJECTPROPERTY(

                        OBJECT_ID(

                            QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)

                             ), 'IsMSShipped'

                               ) = 0

        )

 

        WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)

 

        BEGIN

            SET @ColumnName =

            (

                SELECT MIN(QUOTENAME(COLUMN_NAME))

                FROM     INFORMATION_SCHEMA.COLUMNS

                WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)

                    AND    TABLE_NAME    = PARSENAME(@TableName, 1)

                    AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')

                    AND    QUOTENAME(COLUMN_NAME) > @ColumnName

            )

 

            IF @ColumnName IS NOT NULL

 

            BEGIN

                INSERT INTO #Results

                EXEC

                (

                    'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) 

                    FROM ' + @TableName + 'WITH (NOLOCK) ' +

                    ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2

                )

            END

        END    

    END

 

    SELECT ColumnName, ColumnValue FROM #Results

END

Tags:

TextBox

Tag cloud

    RecentPosts