Category Archives: Nuget

Nuget

The type or namespace name 'WebGrid' could not be found (are you missing a using directive or an assembly reference?)

i am getting this kind of error message while running the programm as compilation error. previously i didn’t get this kind of error message but suddenly i am getting the error. 

previously in all modules it’s working fine but suddenly in all the modules i am getting the same error. 

what’s problem behind on this

Hi,

did you uninstall / update a nuget package related to System.Web.Helpers?

Grz, Kris.

no i didn’t uninstall any package but in references i have this System.Web.Helpers

Hi,

do you have a CVS ready so that you can go back in history of your code to a state where it worked? If so check the differences. Likely some using statement got lost.

Grz, Kris.

Hi,

You may not have "WebGrid.*.dll" with your project, or you may update your project, and "WebGrid.*.dll" is incompatible. Or accidentally deleted from your project dll libs.

You may need to add reference again to your project.

Please check carefully and Have fun

i was installed the webgridmvc from nuget also but it is not working

Hi,

Make sure that name is "WebGrid" or "WebGridMVC". It is case sensitive. Please check.

I’ll try to test it and come to you then.

WebGrid grid = new WebGrid();

i am using this thing only from the entire project upto few days back also it’s working fine. right now we are trying to add a new view with the webgrid then we are getting this

problem and we run the entire project which have this webgrid all are getting the same error. we shocked what happend and how to regetting the Webgrid we dont want to change any other things right now because i have so many forms this webgrid

Hi,

If you install webgridmvc, you must use "@using WebGridMvc;" for the nameSpace.

Please post the detail errors.

if i changed to WebgridMvc then i have to change my entire code where i have this webgrid this will again long time taken thing 

 Layout = "~/Views/Shared/_AdminLayout.cshtml";
Line 5:  
Line 6:      WebGrid grid = new WebGrid();
Line 7:      grid.Bind(Model,
Line 8:                autoSortAndPage: true

CS0246: The type or namespace name ‘WebGrid’ could not be found (are you missing a using directive or an assembly reference?)

this error i am getting when i run the page 

Are you using the appropriate @using statement?  If so, is it at the top of the page or the web.config file?  If it is in the web.config then try closing VisualStudio then re-opening it as that config setting isn’t dynamically processed as you change it. 
Also check the appropriate dll is in the bin folder.  Something else you can test to see if it is a missing assembly or missing "using" is to use the full classname, eg the namespace and classname, and see if the class is found then.

the problem is solved after remove the System.Web.Helpers from the references and add it again. But i got another problem while do it when  i tried to run the program i am getting the following error

An exception of type ‘System.TypeLoadException’ occurred in Microsoft.Owin.Security.Cookies.dll but was not handled in user code

Additional information: Could not load type ‘Microsoft.Owin.Security.AuthenticationDescription’ from assembly ‘Microsoft.Owin, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35′.

Hi Siva_540,

Thanks for your post.

Siva_540

Additional information: Could not load type ‘Microsoft.Owin.Security.AuthenticationDescription’ from assembly ‘Microsoft.Owin, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35′.

You can try install the package from Manage NuGet packages

Microsoft.Owin.Security

Hope this can be helpful.

Best Regards,

Eileen

i have already this in my project

[RESOLVED]Layout Needs a Model

Hi All,

I am working on a project for which the UI was created by someone else.  The project has a Partial View called _ApplicationLayout.cshtml that renders on every view page in the project.   It also hosts several partial views, one of which is the "_Comments.cshtml"
view in which I need to display all of the comments from the database that are associated with the application in the right bar of the layout.  I cannot use a View Model in the _Comments.cshtml partial, because it is rendered in the _ApplicationLayout.cshtml
and of course the View Model clashes with all of the other View Models throughout the project.  Can anyone tell me just how can solve this problem?  The comments do need to show on every page (view) in the project.

You can do it via two different ways,

  1. Call @Html.RenderAction  rather than partial to render the result of an action method, that will give you chance to separate out the code with strongly typed model
  2. Create a base controller and initialize the data and assign it to ViewBag which is required for comments view, now all controllers will inherit from base controller and they will have the data available.

I would prefer the first approach as it is a MVC way of doing things and avoid any accidental miss of controller inheritance.

Either move the comments-partial to the actual View, or replace the Partial helper with an Action helper and pass it an ID/value to process data and return a partial view

Example–

Instead of:

@Html.Partial("_Comments")

do:

@Html.Action("GetComments", new { id = X })

where X could be a ViewBag.Value or a URL parameter, example:

@Html.Action("GetComments", new { id = ViewBag.BlogID })

public ActionResult GetComments(int id)
{
  var comments = db.Comments.Where(c => c.BlogID == id).ToList();

  return PartialView("_Comments", comments);
}

The problem is that there  will be a list of comments, and there is a "textarea" for adding more comments on the fly.  Will the solution you suggested still work?  I don’t have the option of moving the Partial out of the _ApplicationLayout.cshtml.  Also,
how can I specify the controller where the ActionResult is in the code:

@Html.Action("GetComments"new { id = ViewBag.loanApplicationId})
?

You can specify the Controller as another parameter of the Action helper:

@Html.Action("GetComments", "Home", new { id = ViewBag.loanApplicationId })

As for your text-area, just give this input a name that matches the post-action param:

@using Html.BeginForm("AddNewComment"))
{
@Html.Hidden("ApplicationId", ViewBag.loanApplicationId)
<div>
Add Comment: @Html.TextArea("NewComment")
</div>

<input type="submit" value="Submit" />
}

Action:

[HttpPost]
public ActionResult AddNewComment(int ApplicationId, string NewComment)
{
  // use ApplicationId to fetch the record
// add NewComment to the record

return redirectToAction("Index"); }

That’s a fairly simple solution.  If you have questions, ask away

Okay, I think I understand it now.  The only other question I have is if they should add a comment (remember they could be on any View page in the project), Once the comments pane is updated the user is has to return to the same view.  From what I have read
online, this should be some sort of "child action only".  Is that correct?

By the way, you are really awesome to have taken the time to help me!  I wish I could send you a gift!

So what you want to do is use an Ajax form, process the comment, then return a fresh instance of your Partial view back to the main View.  Let’s go through the whole thing, but with the ajax:

1) In your _Layout, you’ve got the Html.Action(…) helper.  We should wrap this in a <div> tag because we’re going to update this after our ajax-post

<div id="commentsDiv">
  @Html.Action("GetComments", "Home", new { id = ViewBag.loanApplicationId })
</div>

2) In your partial view, you’ve got your form that allows the user to add a comment.  We’re going to change this to an Ajax form

@using (Ajax.BeginForm("AddNewComment", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "commentsDiv" }))
{
  @Html.Hidden("AppId", ViewBag.loanApplicationId)
  <div>
    Add Comment: @Html.TextArea("NewComment")
  </div>

  <input type="submit" value="Submit" />
}

3) In the post-action, we process the new comment, then return our *UPDATED* _Comments partial view back to the view

[HttpPost]
public ActionResult AddNewComment(int AppId, string NewComment)
{
  // use ApplicationId to fetch the record
// add NewComment to the record

var comments = db.Comments.Where(c => c.ApplicationId == AppId).ToList();

return PartialView("_Comments", comments); }

And that’s it!  Now it’s important to note that you MUST have the unobtrusive-ajax scripts included in your View.  If you are unsure whether you have these, check your Scripts folder (download them from the NuGet manager if needed).

I received the following error when I tried to run this:

"Additional information: Error executing child request for handler ‘System.Web.Mvc.HttpHandlerUtil"

I tried to run in without the Id in the parameters and just hardcoded the ID in the method just for testing.  Here is what is in my _ApplicationLayout:

  <div id="PageClassDiv" class="@(ViewBag.PageClass) APPLICATION"><!-- page content container-->
        
        @Html.Partial("~/Views/Shared/_NavigationView.cshtml") <!-- Navigation Partial View -->
        @Html.Partial("~/Views/Shared/_SearchAccordionView.cshtml") <!-- Search Accordion Partial View -->

        <!-- All applications should have comments and sidebar ============================================================================================-->
        @Html.Partial("~/Views/Shared/_SideBarView.cshtml");
        @*@Html.Partial("~/Views/Shared/_CommentsView.cshtml");*@
        @Html.Action("GetComments", "LoanApplication")
        
        <!-- content ============================================================================================-->
        @if (angularEnabled)
        {
            <div class="container" ng-app="@angularAppName">@RenderBody()</div>
        }
        else
        {
            <div class="container">@RenderBody()</div>
        }
    </div><!-- end page content container-->

This is the CommentsView:

<span class="comments">
    <a id="right-menu" href="#right-menu" class="icon-comments"></a>
</span>
<span class="clear"></span>

<div id="sidr-right" class="sidr right">
    <header>
        <h4> Application Notes </h4>
        <a href="#" class="icon-print"></a>
        @using (@Html.BeginForm("Comment", "LoanApplication"))
        {
           @Html.TextArea("Comment")
        @*<textarea cols="100" rows="2" name="Comment" placeholder="Leave Comment ..."></textarea>*@
            <input value="Add Comment" type="submit" />
        }
    </header>

And this is what is in my controller:

  [HttpGet]
        [Route("GetComments")]
        public async Task<ActionResult> GetComments()
        {
            var loanApplicationServiceProxy = base.ServiceProvider.LoanApplicationServiceProxy;

            var comments = await loanApplicationServiceProxy.GetLoanApplicationCommentsByLoanApplicationIdAsync(loanApplicationId) ?? new List<LoanApplicationComment>();
            
            return PartialView("_CommentsView", comments);
        }


 [HttpPost]
        [Route("Comment")]
        public async Task<ActionResult> Comment(FormCollection form)
        {

            var loanApplicationServiceProxy = base.ServiceProvider.LoanApplicationServiceProxy;
            var userId = this.User.Identity.GetUserId();
            string comment = Request.Form["Comment"];
            var applicationComment = new LoanApplicationComment
            {
                Comment = comment,
                CreatedDate = DateTime.Now,
                LoanApplicationId = loanApplicationId,
                Id = Guid.NewGuid(),
                CreatedBy = Guid.Parse(userId)
            };
            await loanApplicationServiceProxy.PutLoanApplicationCommentAsync(applicationComment);

            var comments = loanApplicationServiceProxy.GetLoanApplicationCommentsByLoanApplicationIdAsync(loanApplicationId);

            return View(comments);
         
        }

The code in the Controller "GetComments" never gets hit.  The application throws an error as soon as I try to navigate to a View page that has the comments pane.

BeeDev

The code in the Controller "GetComments" never gets hit.

take off the [HttpGet] and [Route("GetComments")] annotations, and see if that works.

I was able to get it to hit the controller, but I can’t figure out how to actually display the comments.  I’m used to using @model.Comment, or something of the sort, but there is not model, so how do I specify the fields that I need to display?  I must display
the user name, date and time of comment, along with the comment.

This is going beyond the original scope of the question.  If I understand everything correctly, your _Comments partial view displays rows of comments that include user name, date & time of comment, and the comment.

The model for Comment may look something like this (I’m just guessing since you have not posted the actual model):

public class Comment
{
public int CommentId { get; set; } public string Comment { get; set; }
public string UserName { get; set; } public string CDate { get; set; }
public int App_ID { get; set; } }

The model includes a primary index key (CommentId), the other required fields, and also a foreign key reference (App_ID)

The _Comment partial view may then look like this:

@model IEnumerable<AppName.Models.Comment>

<h2>Submit Comment</h2>

@using (Ajax.BeginForm("AddNewComment", "LoanApplication", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "commentsDiv" }))
{
  @Html.Hidden("AppID", ViewBag.loanApplicationId)
  <div>
    Comment: @Html.TextArea("NewComment")
  </div>

  <input type="submit" value="Submit" />
}

<h2>Comments</h2>

@foreach (var item in Model)
{
  <div>
    <dl class="dl-horizontal">
      <dt>Username</dt>
      <dd>@Html.DisplayFor(modelItem => item.UserName)</dd>

      <dt>Date</dt>
      <dd>@Html.DisplayFor(modelItem => item.CDate)</dd>

      <dt>Comment</dt>
      <dd>@Html.DisplayFor(modelItem => item.Comment)</dd>
    </dl>
  </div>
}

To explain, our @model is a LIST of comments that will be passed to the partial view.  At the top I’ve included the AJAX form, which allows a user to submit their comment.  Below the form is the Comments section, which loops through each comment, displaying
the User, the Date, and the Comment (I used DL formatting but you can use TABLE or DIV, etc).  Now when the form posts and finishes processing, we’ll be returning a fresh _Comments partial view, which will replace the old one.  We use "UpdateTargetId" to specify
where to update.

Your AJAX post-action in your "LoanApplication" controller:

[HttpPost]
public ActionResult AddNewComment(int AppID, string NewComment)
{
  // create new comment object
  var comment = new Comment();
  comment.Comment = NewComment;
  comment.UserName = User.Identity.Name;
  comment.CDate = DateTime.Now;
  comment.App_ID = AppID;

  // add comment to db
  db.Comments.Add(comment);
  db.SaveChanges();

// query new comments list and return to partial view var comments = db.Comments.Where(c => c.App_ID == AppID).ToList(); return PartialView("_Comments", comments); }

I’ve commented this for explanation.

Your _Layout view now only needs to have the initial Action helper inside a named DIV

<div id="commentsDiv">
  @Html.Action("GetComments", "LoanApplication", new { id = ViewBag.loanApplicationId })
</div>

As said earlier, once the AJAX form posts, a new version of _Comments partial view will replace the contents of "commentsDiv".

Lastly, the "GetComments" action (in the LoanApplication controller):

public ActionResult GetComments(int id)
{
  var comments = db.Comments.Where(App_ID == id).ToList();

  return PartialView("_Comments", comments);
}

And that’s it.  There’s the entire solution…  If all of this works for you, please take a moment to mark all my responses as answers, as they all answer each of your subsequent questions.  Thanks.

Okay, I figured out that I can put a model in the _CommentsView.cshtml since it is being rendered with an @Html.Action.  Thanks for ALL of your help!  You are awesome!!!

[RESOLVED]fast paging for large numbers of data

which is the easy way to create fast paging for large amount of data more than 10 thousand

tried out ajax paging but taking too much time

nuget paged list fetch all the data which makes the site slow

now how to do the paging please suggest

plus it has a search form i want a paging which maintain search result for it

Hi,

For large amount of data, we need to make paging at the server side. You may see

http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application.

It may help.

Have fun

How many records do you show in 1 page? You need to get only that many records from the DB. Refer below link for DB paging 

http://social.technet.microsoft.com/wiki/contents/articles/23811.paging-a-query-with-sql-server.aspx 

How many records retrieving from db

If you are getting all 10000 from db and handling front-end the here is my idea.

1. Define a store proc in the back to return only the specific page records and count variable

   search proc should have pagesize, pageindex, sort,sortdir, totalcount out and other search parameters

2. So you get only the particular page records from procedure with total_record_count as out

3. Map the page records (returned by store proc) to a model list

4. Send model list to web grid

5. Design asp.net mvc web grid with this result model list and use webgrid.bind method where you can total_record_count) to let the webgrid to render paging

Try DataTables JQuery control. This is free and has a option to fetch page by page using ajax. I used it earlier and worked well. Please see this blog for more information

jQuery
DataTables and ASP.NET
MVC
Integration – Part I

[RESOLVED]Download form to Pdf on button click

Can anyone help me download the selected form on button click to pdf  in MVC ….

or anyother way to do it.

So you need to convert a form to PDF?  I use the NuGet package "Rotativa" to convert anything to PDF.  There’s good documentation on it as well

http://www.codeproject.com/Articles/335595/Rotativa-how-to-print-PDF-in-Asp-Net-MVC

How to add it in my project???

can u suggest me pls

?

You can use Nuget to install it. Go to the Nuget console manager and run the command (as mentioned in the post)

Install-Package Rotativa

For information on how to run Nuget from console see the below post

http://docs.nuget.org/docs/start-here/Using-the-Package-Manager-Console

i have installed Rotativa in my project..

but i m not able to proceed furthur;

can u provide me with sample video for downloading form on button click

Try downloading the demo from the site and run it

https://github.com/webgio/Rotativa/tree/master/Rotativa.Demo

I m getting this error how do i resolve it?

Error 19 The type or namespace name ‘ControllerContext’ could not be found (are you missing a using directive or an assembly reference?) E:PersonalInformationLearningAjaxRotativa-PartialViewAsPdfRotativa-PartialViewAsPdfRotativaAsPdfResultBase.cs 229
44 Rotativa

Can you explain little bit more on what you want to do on the button click. What data you want to convert into pdf and where does this data reside?

Also are you ok with use commercial products which will simplify your work?

I have two buttons on everypage when i view data of a particular client …..print button and download button//…..

print is ok…

now i need code for downloading the particular html page to pdf ……

can u help me with this?

Is it ok to pass your data to a third party website which converts your page to pdf. If yes try this

<a href="javascript:void(window.open('http://www.htmltopdfconverter.net/?convert='+window.location))">Convert To PDF</a>

Also check this stack overflow
convert HTML ( having Javascript ) to PDF using java / javascript

[RESOLVED]Can I use the latest version of TinyMce with mvc5?

I guess the subjects says it all but has anyone done this and if so is there a tutorial anywhere?

Cheers,

Mike.

tinymce is strictly  client side. Its works with any server code. see the tutorials on their site. server side it just a textarea.

  @Html.TextArea("nameOfField")

be sure to add [AllowHtml] to the post back model field.

Yes but I need to use @Html.EditorFor to populate the TextArea with the data in an Edit view.

As Bruce mentions, the TinyMCE Editor is purely client-side and has nothing to do with MVC specifically. You should be able to use it as long as you have any fields that generate a <textarea> element.

It should be noted that you don’t have to use an Html.EditorFor() helper to populate your element. You could explicitly use the Html.TextAreaFor() to ensure that an actual <textarea> element is rendered and then apply the appropriate client-side code to
initialize the TinyMCE.

Complete Example

  1. Create an Project that targets MVC 5.
  2. Add the latest TinyMCE Package via NuGet (Right-click Solution > Manage NuGet Packages > Search for "TinyMCE" > Install the first "TinyMCE" package that appears).
  3. Create an Example Controller with a class that will be equivalent to your Model as seen below :
    public class TinyMCEController : Controller
    {
            // An action to display your TinyMCE editor
            public ActionResult Index()
            {
                return View();
            }
    
            // An action that will accept your Html Content
            [HttpPost]
            public ActionResult Index(ExampleClass model)
            {
                return View();
            }
    }
    
    // An example class to store your values
    public class ExampleClass
    {
            // This attributes allows your HTML Content to be sent up
            [AllowHtml]
            public string HtmlContent { get; set; } 
    
            public ExampleClass()
            {
    
            }
    }
  4. Create a View that will wire up your TinyMCE Editor and will contain the necessary code to post your HTML content :
    <!-- This View uses your Model -->
    @model TinyMCE.Controllers.ExampleClass
    <!DOCTYPE html>
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>TinyMCE Example</title>
        <!-- TinyMCE Script Reference -->
        <script src="~/scripts/tinymce/tinymce.min.js"></script>
        <!-- Script to wire up your TinyMCE editor -->
        <script type="text/javascript">
            // Initialize your tinyMCE Editor with your preferred options
            tinyMCE.init({
                // General options
                mode: "textareas",
                theme: "modern",
                // Theme options
                theme_advanced_buttons1: "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
                theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
                theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
                theme_advanced_buttons4: "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
                theme_advanced_toolbar_location: "top",
                theme_advanced_toolbar_align: "left",
                theme_advanced_statusbar_location: "bottom",
                theme_advanced_resizing: true,
    
                // Example content CSS (should be your site CSS)
                content_css: "css/example.css",
            });
        </script>
    </head>
    <body>
        <!-- This will automatically post to your Index method (that is decorated with a HttpPost attribute) -->
        @using (Html.BeginForm()) 
        {
            @Html.AntiForgeryToken()
            <div>
                <!-- This will contain your HtmlContent and use the TinyMCE editor-->
                @Html.TextAreaFor(model => model.HtmlContent)
               
                <input type="submit" value="Create" />
            </div>
        }
    </body>
    </html>
  5. Now if you navigate to your Index Action, you should see the following :
  6. And then if you Submit it, you should see your HTML Content available in your Controller :

This should be all you need to wire everything up.

Thanks Rion,

That was easier than installing the MVC version Smile

Cheers,

Mike

[RESOLVED]Always filtering Index View on Bool Entity / Displaying only a subset of data

I would like to have the index view (code below) always filter the data on a bool entitiy so that only a subset of the database displays – not the entire database.

If anyone could point me in the right direction, I would appreciate it.

Index.cshtml

@model PagedList.IPagedList<GenericWebApplication.Models.Class_EntitySet01>
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />

@{
    ViewBag.Title = "Class_EntitySet01";
}

<h2>Class_EntitySet01</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>

@using (Html.BeginForm("Index", "Class_EntitySet01", FormMethod.Get))
{
    <p>
        Find by name: @Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
        <input type="submit" value="Search" />
    </p>
}

<table>
    <tr>
        <th>
            @Html.ActionLink("Last Name", "Index", new { sortOrder = ViewBag.NameSortParm, currentFilter = ViewBag.CurrentFilter })
        </th>
        <th>
            First Name
        </th>
        <th>
            @Html.ActionLink("Enrollment Date", "Index", new { sortOrder = ViewBag.DateSortParm, currentFilter = ViewBag.CurrentFilter })
        </th>
        <th></th>
    </tr>

        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Property_Entity01)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Property_Entity02)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Property_Entity21)
        </td>

        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}

</table>

<br />
Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount

@Html.PagedListPager(Model, page => Url.Action("Index",
    new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))

Class_EntitySet01Controller.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using GenericWebApplication.Models;
using GenericWebApplication.DAL;
using PagedList;
using System.Data.Entity.Infrastructure;

namespace GenericWebApplication.Controllers
{
    public class Class_EntitySet01Controller : Controller
    {
        private GenericWebApplicationContext db = new GenericWebApplicationContext();

        // GET: /Class_EntitySet01/
        public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page)
        {
            ViewBag.CurrentSort = sortOrder;
            ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;           
            
            
            var class_entityset01s = from s in db.Class_EntitySet01s
                           select s;

            if (!String.IsNullOrEmpty(searchString))
            {
                class_entityset01s = class_entityset01s.Where(s => s.Property_Entity01.ToUpper().Contains(searchString.ToUpper())
                                       || s.Property_Entity02.ToUpper().Contains(searchString.ToUpper()));
            }
            
            switch (sortOrder)
            {
                case "name_desc":
                    class_entityset01s = class_entityset01s.OrderByDescending(s => s.Property_Entity01);
                    break;
                case "Date":
                    class_entityset01s = class_entityset01s.OrderBy(s => s.Property_Entity21);
                    break;
                case "date_desc":
                    class_entityset01s = class_entityset01s.OrderByDescending(s => s.Property_Entity21);
                    break;
                default:
                    class_entityset01s = class_entityset01s.OrderBy(s => s.Property_Entity01);
                    break;
            }

            int pageSize = 3;
            int pageNumber = (page ?? 1);

            return View(class_entityset01s.ToPagedList(pageNumber, pageSize));
        }

        // GET: /Class_EntitySet01/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Class_EntitySet01 class_entityset01 = db.Class_EntitySet01s.Find(id);
            if (class_entityset01 == null)
            {
                return HttpNotFound();
            }
            return View(class_entityset01);
        }

        // GET: /Class_EntitySet01/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /Class_EntitySet01/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Property_Entity01,Property_Entity02,Property_Entity21")] Class_EntitySet01 class_entityset01)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Class_EntitySet01s.Add(class_entityset01);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }
            return View(class_entityset01);
        }

        // GET: /Class_EntitySet01/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Class_EntitySet01 class_entityset01 = db.Class_EntitySet01s.Find(id);
            if (class_entityset01 == null)
            {
                return HttpNotFound();
            }
            return View(class_entityset01);
        }

        // POST: /Class_EntitySet01/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ID,Property_Entity01,Property_Entity02,Property_Entity21")] Class_EntitySet01 class_entityset01)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Entry(class_entityset01).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }
            return View(class_entityset01);
        }

        // GET: /Class_EntitySet01/Delete/5
        public ActionResult Delete(int? id, bool? saveChangesError = false)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            if (saveChangesError.GetValueOrDefault())
            {
                ViewBag.ErrorMessage = "Delete failed. Try again, and if the problem persists see your system administrator.";
            }
            Class_EntitySet01 class_entityset01 = db.Class_EntitySet01s.Find(id);
            if (class_entityset01 == null)
            {
                return HttpNotFound();
            }
            return View(class_entityset01);
        }

        // POST: /Class_EntitySet01/Delete/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id)
        {
            try
            {
                Class_EntitySet01 class_entityset01 = db.Class_EntitySet01s.Find(id);
                db.Class_EntitySet01s.Remove(class_entityset01);
                db.SaveChanges();
            }
            catch (RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.
                return RedirectToAction("Delete", new { id = id, saveChangesError = true });
            }
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

__________________________________________________________________

Programming Environment:

    Visual Studio 2013
    .NET 4.5
    Entity Framework 6 (EntityFramework 6.1.0 NuGet package)
    OS: Windows 7

Project Based On:
Getting Started with Entity Framework 6 Code First using MVC 5

http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

var class_entityset01s = from s in db.Class_EntitySet01s
                           where s.SomeField == true
                           select s;

Thank you SO much!

[RESOLVED]Implement Membership Concept in MVC 4 Empty Project

hi 

i want to implement asp.net membership concept (that is  implement in MVC 4 internet application Example) in my mvc 4 Empty Project

any one please guide me.

thanks in advance.

Hello Ananth.G Please check the following sample implementation of the Membership Provider on MSDN

http://msdn.microsoft.com/en-us/library/vstudio/6tc47t75%28v=vs.100%29.aspx
It will help you understand how to implement and use the Membership system of ASP.NET.

If you want some more resources about managing your users and many more in your application you can check ASP.NET Identity http://www.asp.net/identity It’s the evolution of ASP.NET Membership system and it’s much
more complete. You can see their differences here

http://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity

If you need any extra information and guidance do not hesitate to ask,

Giorgos

You can use Nuget to install the membership onto your empty project. Please take a look at this Nuget package

https://www.nuget.org/packages/SecurityGuard.MVC4

There are several different types of membership packages in Nuget. Please check this and install what is appropriate for your scenario

Top 20 NuGet packages for membership

Hello Prasanna sir

that security guard was working fine.

is it possible to use existing database for this package.

Note :

* That database already contains some tables.

Ananth.G

is it possible to use existing database for this package

Please check the web.config for the database connection string and modify it accordingly.

ya sir its working.

actually previously I got error because my existing db have the table called Users

so conflict occur from new table and exist one. so only  I will get error.

now its fine I understood.

Thank u sir.

Thanks to all.

hi sir,

after installed SecurityGuard.MVC4

Areas Folder in Created inside Application.

suppose i enter into Dashboard Index,i got error like this

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Configuration.Provider.ProviderException: The Role Manager feature has not been enabled.

Please give me a solution.

[RESOLVED]How to Implement a CKeditor in MVC

Hi,

I am newibe in MVC. I have a visual studio 2012. I want to create an mvc application.In this Application , want to use CkEditor In MVC.I want to enter some text in CK editor textbox and insert this text into a table as html string.Am using Sql server 2008
.Want to insert the data through ADO.net class and not through entiity framework.Pls provide some sample solution

Regards,

Dileep

 

for the ckeditor open up nuget and search for ckeditor.mvc

first of all you have to know examples aren’t just given here it’s a support forum not a school or whatever.

the easiest way for you to get this to work is with a viewmodel 

in this viewmodel you make a property and give it the attribute [allowhtml] you can use attributes on these properties something like:

public class BlogEntry {

    [AllowHtml] 
    public string BlogText {get;set;}
 }

now make a new method in your controller TestMethod

        public ActionResult TestMethod()
        {
            return View(new BlogEntry());
        }

        [HttpPost]
        public ActionResult TestMethod(BlogEntry be)
        {
             //send to db
            return View(be);
        }

in your view you need to reference a model at the top of the page, something like:

@model MyProject.ViewModels.BlogEntry

it is important when you use custom inputs like the ckeditor that you fill up id and name attributes on there the same as your model

in this case BlogText so a normal input would look like:

<input type="text" id="BlogText" name="BlogText" />

if you put that within a form tag with a submit button in it it will automaticly fill the model in your controller on post

hope this helps you a little bit :)

Hi,

Can ypuls eaplian step by step or samples with details.

Regards,

Dileep Sanker

Hi dileep,

Thanks for your post.

dileep Sanker

Can ypuls eaplian step by step or samples with details.

You can follow this:

Using CKEditor with Razor for .NET MVC 3

http://peterkeating.co.uk/using-ckeditor-with-razor-for-net-mvc3/

and here is a similar thread:

http://www.experts-exchange.com/Programming/Microsoft_Development/Q_28257325.html

Hope this can be helpful.

Best Regards,

Eileen

[RESOLVED]level 2 transparency causes all methods in AllowPartiallyTrustedCallers

Hi,

i am using PagedList Nuget package in my asp.net mvc 5 application.

below is my source which i am trying to:

@Html.PagedListPager(Model, page => Url.Action("StudentList",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))

when i am using it on my view, it is throwing an exception:

System.TypeAccessException was unhandled by user code
  HResult=-2146233021
  Message=Attempt by security transparent method 'PagedList.Mvc.HtmlHelper.PagedListPager(System.Web.Mvc.HtmlHelper, PagedList.IPagedList, System.Func`2<Int32,System.String>)' to access security critical type 'System.Web.Mvc.MvcHtmlString' failed.

Assembly 'PagedList.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=abbb863e9397c5e1' is marked with the AllowPartiallyTrustedCallersAttribute, and uses the level 2 security transparency model.  Level 2 transparency causes all methods in AllowPartiallyTrustedCallers assemblies to become security transparent by default, which may be the cause of this exception.
  Source=PagedList.Mvc
  TypeName=""
  StackTrace:
       at PagedList.Mvc.HtmlHelper.PagedListPager(HtmlHelper html, IPagedList list, Func`2 generatePageUrl)
       at ASP._Page_Views_Registration_StudentList_cshtml.Execute() in c:UsersmaifsSkyDriveSchoolManagementSystemSMSAppViewsRegistrationStudentList.cshtml:line 57
       at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
       at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
       at System.Web.WebPages.StartPage.RunPage()
       at System.Web.WebPages.StartPage.ExecutePageHierarchy()
       at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
       at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
       at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
       at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
  InnerException: 

i tried to use these attributes in assemblyinfo.cs

[assembly: SecurityRules(SecurityRuleSet.Level2)]

and 

[assembly: AllowPartiallyTrustedCallersAttribute] but it didn’t work. Kindly guide me . thanks

Hi softech,

For this issue, it seems there is the issue in that PagedList.MVC package.

Please upgrade the package to the least version. (PagedList.Mvc 4.5)

# PagedList.Mvc 4.5.0

https://www.nuget.org/packages/PagedList.Mvc

There is a related thread that can help you:

http://forums.asp.net/t/1939805.aspx

Best Regards

Starain Chen

Thanks Starain.

[RESOLVED]MVC Partial View

Hi,

I am quite new to MVC etc. I want to know something on postings by partial views.

I have a page which has a graph on. The graph is generated by a partial view. Now what I want to do is have date ranges in which the user can select to display data for.

But when I do a post from the form on the partial view, it just basically goes to a view displaying the graph only, and also removes the my form tags.

Any help would be appreciated in getting what I need (VIA Jquery might be the way?)

Thanks

Kobie

You may want to use the Ajax-Form helper to post your form and retrieve a new partial view (with your graph) and replace your old graph

@using (Ajax.BeginForm("GetGraph", new AjaxOptions { HttpMethod = "POST", TargetUpdateId = "graphDiv" }))
{
  Date From: @Html.TextBox("DateForm") <br />
  Date To: @Html.TextBox("DateTo")

  <input type="submit" value="Submit" />
}


<div id="graphDiv">
  // your graph goes here
</div>

The above uses the ajax form helper, specifying the graph’s div container for where we want to insert the new graph (based on the date fields).

The graph action:

[HttpPost]
public ActionResult GetGraph(DateTime DateFrom, DateTime DateTo)
{
  var graphData = /* use the date params above to generate your graph's data */;

  return PartialView("GraphPartial", graphData);
}

All this action does is it takes your date fields from the form and uses them to generate your graph’s data.  Then we pass that data to our graph’s partial view.  You’ll need to specify the name of that partial view (I used ‘GraphPartial’)

Last little note: in order to use AJAX, you’ll need to include the jquery and ‘unobtrusive-ajax’ scripts in your View.  They should be located in your /Scripts folder just like any other jquery script.  If you don’t have the unobtrusive-ajax script, it can
be downloaded using the NuGet Package Manager for your project (under Tools menu).

Hope that helps

Hi,

Exactly how I want it, I will try and let you know of the results.

Ok no luck, it still throws away my the rest of the page and then just displays the graph, but now with no data. :(

main view :

//Think its got something to do with this.

@using (Ajax.BeginForm("LeadChart", "Chart", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "myGraph" }))
{ 
<div>@Html.TextBoxFor(x => x.ChartData.DateFrom) </div>
<div>@Html.TextBoxFor(x => x.ChartData.DateTo) </div>
<div><input type="submit" value="Get data" /></div> 
}

<div id="myGraph">
         @{ Html.RenderPartial("LeadChart", Model.ChartData);}
</div>

Leadchart controller:

//So this works fine

[HttpPost]
public ActionResult LeadChart(Chart chart)
{
     chart.DateFrom = Convert.ToDateTime(chart.DateFrom);
     chart.DateTo = Convert.ToDateTime(chart.DateTo);
     var data = chart.ChartData; 
     return PartialView(chart);
}

1) change your form-action to not be the same name as the partial view

@using (Ajax.BeginForm("GetLeadChart", "Chart", ....

2) update the action name to reflect this change

[HttpPost]
public ActionResult GetLeadChart(Chart chart)
{
...

3) did you mean to use data instead of "chart"?


return PartialView("LeadChart", data);

4) lastly, if after posting, your view changes to just the partial chart view, it means your AJAX is not working.  If it’s not working after these suggestions, please post your View’s HTML source

Hi,

Hehehe so stupid mistake on my side. My Jquery was outdated…

Thanks a lot for the help!!Embarassed