Rectangle 27 8

Read here on how to use the Razor view engine inside your Web API controller. The interesting part is using the RazorEngine NuGet package to do the heavy lifting.

c# - ASP.NEt MVC using Web API to return a Razor view - Stack Overflow

c# html asp.net-mvc razor asp.net-web-api
Rectangle 27 3

I think, your problem is not in "passing the list" but in "saving selected list items one by one". Sending 2k list from view to controller is not that heavy (well, it is, but it should still work not too slow). But if you perform N database operations for N selected items, this is where you have your bottle neck.

You have 2 options:

  • Save selected item as soon as user selects it.

Ok, but how can I send the List<T> only with the selected objects?

@AntnioFilho you can use jQuery: $("#select-list").val() if you want to send all selected values on form submit or you can use ajax to send values one by one when user selects item.

Sorry, but I'm a little confused. I'll have to do something like this? " $.ajax({ url: '@Url.Action("MyAction", "MyController")', type: 'POST', data: $("#select-list").serialize(), success: function (result) { alert('ok'); } });"

@AntnioFilho yes, something like that. Get values and then pass them using Ajax. But I would recommend to consider saving values when user selects them.

c# - Best way to pass big List from View to Controller - Stack Over...

c# asp.net-mvc model-view-controller view controller
Rectangle 27 20

You just need to test the filter itself. Just create an instance and call the OnActionExecuted() method with test data then check the result. It helps to pull the code apart as much as possible. Here's an example I've written. Most of the heavy lifting is done inside the CsvResult class which can be tested individually. You don't need to test the filter on an actual controller. Making that work is the MVC framework's responsibility.

public void AcceptsTypeFilterJson_RequestHeaderAcceptsJson_ReturnsJson()
{
    var context = new ActionExecutedContext();
    context.HttpContext = // mock an http context and set the accept-type. I don't know how to do this, but there are many questions about it.
    context.Result = new ViewResult(...); // What your controller would return
    var filter = new AcceptTypesAttribute(HttpContentTypes.Json);

    filter.OnActionExecuted(context);

    Assert.True(context.Result is JsonResult);
}

How do I unit test a custom ActionFilter in ASP.Net MVC - Stack Overfl...

asp.net-mvc unit-testing tdd actionfilterattribute
Rectangle 27 19

You just need to test the filter itself. Just create an instance and call the OnActionExecuted() method with test data then check the result. It helps to pull the code apart as much as possible. Here's an example I've written. Most of the heavy lifting is done inside the CsvResult class which can be tested individually. You don't need to test the filter on an actual controller. Making that work is the MVC framework's responsibility.

public void AcceptsTypeFilterJson_RequestHeaderAcceptsJson_ReturnsJson()
{
    var context = new ActionExecutedContext();
    context.HttpContext = // mock an http context and set the accept-type. I don't know how to do this, but there are many questions about it.
    context.Result = new ViewResult(...); // What your controller would return
    var filter = new AcceptTypesAttribute(HttpContentTypes.Json);

    filter.OnActionExecuted(context);

    Assert.True(context.Result is JsonResult);
}

How do I unit test a custom ActionFilter in ASP.Net MVC - Stack Overfl...

asp.net-mvc unit-testing tdd actionfilterattribute
Rectangle 27 2

The best solution would be to simply expose your data to them and let them render it whichever way they want. You could have your controllers simply spit out JSON for them and let them do with it as they please. This all assumes there isn't any heavy lifting being done on the view, however.

asp.net - MVC: View with remote hosted layout - Stack Overflow

asp.net asp.net-mvc-3 c#-4.0 razor
Rectangle 27 1

It perhaps isn't ideal, but could you not just create maps for the two references and map them after the fact. You still have to call them seperately, but you're letting AutoMapper do the heavy mapping, rather than filling your controller with your own maps.

public ActionResult FooDetails(string id)
{
    using(var session = this.documentStore.OpenSession())
    {
        var foo = session.Load<Foo>(id).Include(....);
        var alpha = session.Load<Alpha>(foo.AlphaId);
        var beta = session.Load<Beta>(foo.BetaId);

        // null checks

        var fooViewModel = Mapper.Map<FooViewModel>(foo);
        fooViewModel.Alpha = Mapper.Map<AlphaViewModel>(alpha);
        fooViewModel.Beta = Mapper.Map<BetaViewModel>(beta);

        return View(fooViewModel);
    }
}

I haven't used AutoMapper all that much, but perhaps you can pass in child objects through the Map function (to feed the ForMember chains on CreateMap)? Perhaps Alexandre's AfterMap suggestion might work, but I don't see how you'd hydrate the 'referenced' children without creating the map inside the controller action (but then you may as well just use ForMember and the Raven session directly and have only one Mapper.Map).

Addition - The AutoMapper documentation suggests a similar method for nested/child maps - https://github.com/AutoMapper/AutoMapper/wiki/Nested-mappings. Although it's more akin to an object reference, rather than a object id reference situation.

I can't comment on other answers yet, but with regard to Pavel's answer - you don't really use Raven in that way, there is no o/r mapping (other than the internal JSON -> object) or data access layer, you just use the Raven session directly (perhaps through a service, but there's certainly no need for a repository or similar). With regards to referencing, byte has it right and as he commented on one of the other answers, the best approach is to store an id reference and use a Raven include - it's the same result and still uses only one request.

c# - ASP.NET MVC model to viewmodel mapping with additional secondary ...

c# asp.net asp.net-mvc automapper ravendb
Rectangle 27 1

I'm not sure how big of a problem this actually is, but the "alternative pattern" to follow in ASP.NET MVC would be to write a JSON ViewEngine. This wouldn't actually be that difficult, since the JSON functionality built into the framework will do much of the heavy lifting for you.

I do think that this would be a better design, but I'm not sure it's so much better that it's worth going against the "official" way of implementing JSON.

clever :) i haven't thought it through yet but that sounds workable. id be interested to see if anyone from MS chimes in on this issue

asp.net mvc - Should my MVC controller really know about JSON? - Stack...

asp.net-mvc json design-patterns
Rectangle 27 1

I'm not sure how big of a problem this actually is, but the "alternative pattern" to follow in ASP.NET MVC would be to write a JSON ViewEngine. This wouldn't actually be that difficult, since the JSON functionality built into the framework will do much of the heavy lifting for you.

I do think that this would be a better design, but I'm not sure it's so much better that it's worth going against the "official" way of implementing JSON.

clever :) i haven't thought it through yet but that sounds workable. id be interested to see if anyone from MS chimes in on this issue

asp.net mvc - Should my MVC controller really know about JSON? - Stack...

asp.net-mvc json design-patterns
Rectangle 27 1

One way you could reduce the number of lines in the controller is to abstract out some of the hard-coded datasets into a static JavaScript file. Anything you feel that may be heavy in the controller that could be abstracted out could potentially be an area for improvement.

An example could be to create a global data variable where you could access the variables on that page.

(function(global){
  global.data = {
    names: ['Jane', 'John', 'Mary', 'Michael', 'Ryan', 'Rachel']
  };
})(this);
(function(global){
  app.controller('MainController', function($log){
    this.message = "Hello, world!";
    //Usage of the global variable here.
    this.names = global.data.names;
    this.click = function(){
      global.handlers.onclick(this);
    };
  });
})(this);

Here's an example of usage in the view.

<!DOCTYPE html>
<html ng-app="TestModule">

  <head>
    <link rel="stylesheet" href="style.css">
    <!-- Reference to Angular on CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script>
    <!-- Reference to external data sets -->
    <script src="data.js"></script>
    <!-- Reference to external event handlers -->
    <script src="handlers.js"></script>
    <!-- Angular module init -->
    <script src="module.js"></script>
    <!-- Controller init -->
    <script src="maincontroller.js"></script>
  </head>

  <body>
    <div ng-controller="MainController as main">
      <h3>{{ main.message }}</h3>
      <div>
        <h2>Names from the global data.js file:</h2>
        <h3 ng-repeat="n in main.names">{{ n }}</h3>
      </div>
      <div>
        <input type="button" ng-click="main.click()" value="Click me!" />
      </div>
    </div>
  </body>

</html>

javascript - How to organize and reduce AngularJS controller size? - S...

javascript angularjs angularjs-directive angularjs-controller
Rectangle 27 9

This is what i have done in my rails mvc project with heavy javascript, i have created a separate namespace for the controllers in js which resembles the rails controller

class BusinessController
   def new
   end  
   def index
   end
end

and

Var Business =  {
      init : function(action) {
         //code common to the Business module
         //even add the common jquery doc ready here, its clean
         //and call the page specific action
         this[action]();
      },
      new : function() {
             // check jquery document ready code here, thats relevant to this action
             //New rental page specific code here
      },
      index : function() {
             //  check jquery document ready code here, thats relevant to this action
             //index rental page specific code here 
      }
}

and on the view code(server side) just initiate the page specific js code by

<script type="text/javascript"> 
 <%= controller_name %>.init('<%= controller.action_name %>'); 
//which will render to
//  Business.init(index);
</script>

You can pretty much tweak this to make it work in any language. And this approach doesn't care whether you have a single file or multiple files.

Very neat solution! I like the use of plain ol' JS and how it marries up to your controller. this would lose some client side caching by spitting out the document ready stuff inline on the page, but it's negligible being only one line long! I'm not overly keen on spitting out JS server side, but it's a fair approach considering it's very generalised. I've almost completed a jQuery plugin to hook things up. I'll post it here when i'm done if you'd like to check it out - just need a snappy name now! Thanks for the food for thought :)

@mr.nicksta, i am glad you liked it... i have been following this approach for quite some time.. its clean and very easy to manage...

Good to hear it's been tried and tested too. Is there an error in your example? <%= controller_name %>.init<%= controller.action_name %> would output Business.initindex, right? Parentheses are missing :)

yep, it should have been like <%= controller_name %>.init('<%= controller.action_name %>');

this was my favourite answer. In terms of cleanliness, maintainability and simplicity it did exactly what i asked. Even though i cannot actually use this approach because i'm stuck with a WebForms app at the moment, i will award you the bounty for the excellent, well thought-out answer. Enjoy your 100 points :-)

javascript - managing document.ready event(s) on a large-scale website...

javascript jquery maintainability document-ready
Rectangle 27 3

Case 1 : Using angularJs alone: To execute a method on page load, you can use ng-init in the view and declare init method in controller, having said that use of heavier function is not recommended, as per the angular Docs on ng-init:

This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit, such as for aliasing special properties of ngRepeat, as seen in the demo below; and for injecting data via server side scripting. Besides these few cases, you should use controllers rather than ngInit to initialize values on a scope.

<div ng-controller="searchController()">
    <!-- renaming view code here, including the search box and the buttons -->
</div>
app.controller('SearchCtrl', function(){

    var doSearch = function(keyword){
        //Search code here
    }

    doSearch($routeParams.searchKeyword);
})

Warning : Do not use this controller for another view meant for a different intention as it will cause the search method be executed there too.

Case 2 : Using Ionic: The above code will work, just make sure the view cache is disabled in the route.js as:

.state('app', {
    url           : '/search',
    cache         : false, //disable caching of the view here
    templateUrl   : 'templates/search.html'   ,
    controller    : 'SearchCtrl'
  })

This only had one up and was at the very bottom, glad I went all the way down, the cache: false did it for me thanks!

angularjs - How to execute angular controller function on page load? -...

angularjs onload
Rectangle 27 3

Case 1 : Using angularJs alone: To execute a method on page load, you can use ng-init in the view and declare init method in controller, having said that use of heavier function is not recommended, as per the angular Docs on ng-init:

This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit, such as for aliasing special properties of ngRepeat, as seen in the demo below; and for injecting data via server side scripting. Besides these few cases, you should use controllers rather than ngInit to initialize values on a scope.

<div ng-controller="searchController()">
    <!-- renaming view code here, including the search box and the buttons -->
</div>
app.controller('SearchCtrl', function(){

    var doSearch = function(keyword){
        //Search code here
    }

    doSearch($routeParams.searchKeyword);
})

Warning : Do not use this controller for another view meant for a different intention as it will cause the search method be executed there too.

Case 2 : Using Ionic: The above code will work, just make sure the view cache is disabled in the route.js as:

.state('app', {
    url           : '/search',
    cache         : false, //disable caching of the view here
    templateUrl   : 'templates/search.html'   ,
    controller    : 'SearchCtrl'
  })

This only had one up and was at the very bottom, glad I went all the way down, the cache: false did it for me thanks!

angularjs - How to execute angular controller function on page load? -...

angularjs onload
Rectangle 27 3

Case 1 : Using angularJs alone: To execute a method on page load, you can use ng-init in the view and declare init method in controller, having said that use of heavier function is not recommended, as per the angular Docs on ng-init:

This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit, such as for aliasing special properties of ngRepeat, as seen in the demo below; and for injecting data via server side scripting. Besides these few cases, you should use controllers rather than ngInit to initialize values on a scope.

<div ng-controller="searchController()">
    <!-- renaming view code here, including the search box and the buttons -->
</div>
app.controller('SearchCtrl', function(){

    var doSearch = function(keyword){
        //Search code here
    }

    doSearch($routeParams.searchKeyword);
})

Warning : Do not use this controller for another view meant for a different intention as it will cause the search method be executed there too.

Case 2 : Using Ionic: The above code will work, just make sure the view cache is disabled in the route.js as:

.state('app', {
    url           : '/search',
    cache         : false, //disable caching of the view here
    templateUrl   : 'templates/search.html'   ,
    controller    : 'SearchCtrl'
  })

This only had one up and was at the very bottom, glad I went all the way down, the cache: false did it for me thanks!

angularjs - How to execute angular controller function on page load? -...

angularjs onload
Rectangle 27 3

The way I like to do this is with RESTful controller actions. You can return JSON and use your calls with JavaScript on your own site. Other websites would almost certainly understand JSON and so they'd be able to consume your API pretty easily. This is much easier to write and test than a heavy WCF layer.

if you could explain the downvote, I'd appreciate it. I can elaborate if necessary.

ASP.NET MVC API or WCF API - Stack Overflow

asp.net-mvc wcf api asp.net-mvc-3 wcf-web-api
Rectangle 27 1

I don't fully understand your code as it is not written in English but as far as I can see your Converter is written badly. As far as I can see you do a toString() and a fromString() basically. This is quite error prone and the way you did it, heavy in performance. It is a better idea to use unique ID's (business or database).

@FacesConverter(value = "aktiListConverter")
public class AktiListConverter implements Converter
{
    private InitialisierungController controller = InitialisierungController.getInstance();

    @Override
    public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2)
    {
        //Get object by it's unique ID
        return controller.getById(Long.parseLong(arg2));
    }

    @Override
    public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2)
    {
        //Return object's unique ID
        return ((DTOAktivitaet) arg2).getId();
    }
}

In stead of using the object as itemLabel (which performs a toString()) use something that generates a nice label like getName() for a person.

itemLabel="#{aktivitaet.nameOrSomething}"
speicherAktiZug()
public class AktiListController
{
    private List<DTOAktivitaet> source;
    private List<DTOAktivitaet> target = new ArrayList<DTOAktivitaet>();
    private DualListModel<DTOAktivitaet> aktis;

    public AktiListController()
    {
        source = controller.getAktivitaeten();
        aktis = new DualListModel<DTOAktivitaet>(source, target);
    }

    //Getters and setters

    public void speicherAktiZug()
    {
        target = aktis.getTarget();

        //target should contain the picked items here.
    }
}

I see you are also using aktiListController.selected but I cannot see what it's used for.

Thank you for your answer! This improved my code a lot. To solve the problem: I accessed the target-list from picklist in the Constructor of my Controller. So logically it was empty. I created a function outside the constructor and took the items there.

jsf - picklist PrimeFaces - How to get data from target-list? - Stack ...

jsf primefaces
Rectangle 27 1

Based on your grammar, I think you got downvoted due to your english skills and this is kind of a duplicate question. Sorry about that but SO tends to be heavy on native English users. Also your question needs more detail to determine what you're trying to accomplish.

You might want to check out Michael Hartl's site for a good introduction. Good Luck

I already try to look for the entire 1 hour in SO. No, I don't do this for the sake of inheritance. Or perhaps inheritence, but I don't want the data to be saved into 1 table. Place begin with A must be saved into table A. Those tables are similar in nature, but too many controllers/models/views/scripts/scss make my Rails looks ugly.

If it looks ugly it probably means you're doing it wrong. To me it sounds like you're trying to achieve the third bullet point, but you're forcing it to confirm to a separate model and table for each. The cruft you're referring to is caused by using the scaffold generator. You only need to generate a Model to get the Model and tables created. Good Luck!

ruby on rails - Many tables 1 controller, model and views - Stack Over...

ruby-on-rails ruby-on-rails-3.2
Rectangle 27 0

As Raja commented, you should build your response controller to handle this logic rather than modifying the jQuery, I have used the same solution and it works great. You might want to do some performance testing and make sure that the LIKE query isn't too heavy though.

Search for multiple words with jQuery Autocomplete - Stack Overflow

jquery autocomplete
Rectangle 27 0

Nothing wrong with this as long as you handle all the heavy lifting in your repositories. You may want to wrap/handle modelstate exceptions in your base controller.

I am actually doing something similar for a large project where users can define their own entities and APIs - ie: one user may want to have users and accounts while another may want to track cars and whatever else. They all use the same internal controller, but they each have their own endpoints.

Not sure how useful our code is to you since we don't use generics (each object is maintained as metadata and manipulated/passed back and forth as JObject dictionaries) but here is some code to give you an idea of what we are doing and maybe provide food for thought:

[POST("{primaryEntity}", RouteName = "PostPrimary")]
public async Task<HttpResponseMessage> CreatePrimary(string primaryEntity, JObject entity)
{
   // first find out which params are necessary to accept the request based on the entity's mapped metadata type
   OperationalParams paramsForRequest = GetOperationalParams(primaryEntity, DatasetOperationalEntityIntentIntentType.POST);

   // map the passed values to the expected params and the intent that is in use
   IDictionary<string, object> objValues = MapAndValidateProperties(paramsForRequest.EntityModel, paramsForRequest.IntentModel, entity);

   // get the results back from the service and return the data to the client.
   QueryResults results = await paramsForRequest.ClientService.CreatePrimaryEntity(paramsForRequest.EntityModel, objValues, entity, paramsForRequest.IntentModel);
        return HttpResponseMessageFromQueryResults(primaryEntity, results);

}

Good luck :) looks very complicated. i would avoid all that.:)

For what you are doing, yes, slight overkill ;). However, the code above allows multiple customer accounts with multiple apps in each account to manage multiple entities using one generic controller (actually we have broken it out into a controller per action type) so not so complex when you consider the problem it has to solve. And if we can use the above code and support thousands of clients with under 100ms response time, you're good to go ;). Anyway, just trying to show another way of accomplishing it as food for thought.

c# - Generic WebApi Controller - Stack Overflow

c# asp.net-mvc generics asp.net-web-api
Rectangle 27 0

As @robert-harvey said, you should utilize libraries like JSON.NET that are already available to do the heavy lifting for you.

Pulled from the JSON.NET API docs: If you create a string json that holds your json, you can read from it with new JsonTextReader(new StringReader(json))

c# - AJAX POST Complex JSON to MVC4 Controller - Stack Overflow

c# ajax json asp.net-mvc-4 data-binding
Rectangle 27 0

I updated the following code using the EditorTemplate to get rid of the heavy switch statements i was using to iterate over the polymorphic collection of derived types.

@for (int i = 0, c = this.Model.Count; i < c; i++)
 {
    var currentItem = this.Model.ElementAt(i);
     @Html.EditorFor(model => currentItem)
 }

I then added the following prefix in all of my EditorTemplates to prevent duplicate name and ids of the controls.

@{
    ViewData.TemplateInfo.HtmlFieldPrefix = Model.ProvinceCode;
}

I created a custom ModelBinder to intercept and bind the form data to create a ViewModel i can use.

[HttpPost]
    public ActionResult UpdateItem([ModelBinder(typeof(ProvinceCustomModelBinder))]ProvinceVM model)

c# - Losing ViewModel on Partial View post back to controller - Stack ...

c# asp.net-mvc