'How to concatenate two data in a ViewData at the razor page in ASP.Net Core?

I created a ViewData[] to populate a drop down list. There are 3 fields (Id, Grade and ClzName) in ViewData[]. I need to set ID field to Id and Value field to Grade+ClzName of the drop down list.

I try it as follows but failed. Any one can please help me to resolve it.

controller.cs

 private void PopulateSelectClassDDL()
        {
            using (_context)
            {
                List<Class> classList = new List<Class>();
                classList = _context.Classes.ToList();               
                ViewData["classList"] = classList;

            }
        }

view.cshtml

  @Html.DropDownList("ClzId", new SelectList((System.Collections.IEnumerable)ViewData["classList"],"Id", "Grade" + "ClzName"))


Solution 1:[1]

Here's how to get behaviour similar to __noSuchMethod__

First of all, here's a simple object with one method:

var myObject = {
    existingMethod: function (param) {
        console.log('existing method was called', param);
    }
}

Now create a Proxy which will catch access to properties/method and add your existing object as a first parameter.

var myObjectProxy = new Proxy(myObject, {
   get: function (func, name) {
       // if property or method exists, return it
       if( name in myObject ) {
           return myObject[name];
       }
       // if it doesn't exists handle non-existing name however you choose
       return function (args) {
           console.log(name, args);
       }
    }
});

Now try it:

myObjectProxy.existingMethod('was called here');
myObjectProxy.nonExistingMethod('with a parameter');

Works in Chrome/Firefox/Opera. Doesn't work in IE(but already works in Edge). Also tested on mobile Chrome.

Creation of proxy can be automated and invisible i.e. if you use Factory pattern to build your objects. I did that to create workers which internal functions can be called directly from the main thread. Using workers can be now so simple thanks to this cool new feature called Proxy. The simplest worker implementation ever:

var testWorker = createWorker('pathTo/testWorker.js');
testWorker.aFunctionInsideWorker(params, function (result) {
    console.log('results from worker: ', result);
});

Solution 2:[2]

I don't believe this type of metaprogramming is possible (yet) in javascript. Instead, try using the __noSuchMethod__ functionality to achieve the effect with property getters. Not cross-browser as it's a Mozilla extension.

var proxy = {
    __noSuchMethod__: function(methodName, args) {
       if(methodName.substr(0,3)=="get") {
          var property = methodName.substr(3).toLowerCase();                             
          if (property in this) {
              return this[property];
          }
       }
    }, color: "red"
 };
 alert(proxy.getColor());           

Solution 3:[3]

You can use the Proxy class.

var myObj = {
    someAttr: 'foo'
};

var p = new Proxy(myObj, {
    get: function (target, propName) {
        // target is the first argument passed into new Proxy,
        // in this case target === myObj
        return 'myObj with someAttr:"' + target.someAttr 
               + '" had "' + propName 
               + '" called on it.';
    }
});
console.log(p.nonExsistantProperty);
// outputs: 
// myObj with someAttr:"foo" had "nonExsistantProperty" called on it

Solution 4:[4]

There is __defineGetter__, __defineSetter__, __lookupGetter__ and __lookupSetter__ in addition to __noSuchMethod__ in SpiderMonkey.

Solution 5:[5]

Although this is an old question I was looking into this today. I wanted to be able to seamlessly integrate code from another context, maybe a different web page or server.

Its the sort of thing that breaks in the long run, but I think its an interesting concept none the less. These things can be useful for mashing code together quickly, ( which then exists for years, buried somewhere ).

var mod = modproxy();

mod.callme.first.now('hello', 'world');

mod.hello.world.plot = 555;

var v = mod.peter.piper.lucky.john.valueOf;
console.log(v);

mod.hello.world = function(v) {
  alert(v);
  return 777;
};

var v = mod.hello.world('funky...');
console.log(v);

var v = mod.hello.world.plot.valueOf;
console.log(v);

mod.www.a(99);
mod.www.b(98);

function modproxy(__notfound__) {

  var mem = {};          
  return newproxy();

  function getter(target, name, receiver, lname) {

    if(name === 'valueOf') {
      lname=lname.slice(1);

      if(lname in mem) {
        var v = mem[lname];
        console.log(`rd : ${lname} - ${v}`);
        return v;
      }

      console.log(`rd (not found) : ${lname}`);
      return;
    }

    lname += '.'+name;
    return newproxy(() => {}, lname);

  } // getter

  function setter(obj, prop, newval, lname) {

    lname += '.' + prop;
    lname = lname.slice(1);
    console.log(`wt : ${lname} - ${newval}`);
    mem[lname] = newval;

  } // setter

  function applyer(target, thisArg, args, lname) {

    lname = lname.slice(1);

    if(lname in mem) {
      var v = mem[lname];

      if(typeof v === 'function') {
        console.log(`fn : ${lname} - [${args}]`);
        return v.apply(thisArg,args);
      }

      return v;

    }

    console.log(`fn (not found): ${lname} - [${args}]`);

  } // applyer

  function newproxy(target, lname) {

    target = target || {};
    lname = lname || '';

    return new Proxy(target, {
      get: (target, name, receiver) => {
        return getter(target, name, receiver, lname);
      },
      set: (target, name, newval) => {
        return setter(target, name, newval, lname);
      },
      apply: (target, thisArg, args) => {
        return applyer(target, thisArg, args, lname);
      }
    });

  } //proxy

} //modproxy

I implemented a valueOf step to read values, because it seems the property is 'get-ted' first.

I dont think its possible to tell at the time the property is 'get-ted' if its going to be invoked or read ( or required for further chaining ).

Its ok for single level properties. The property is either there or its not and either the required type or its not.

I'll work on it further, looking at promises for async/await routines, proxying existing objects and finer control of how properties are accessed when I am more familiar with how the code behaves and is best implemented.

I created a repository on GitHub: modproxy.js/README.md

CodePen: modproxy.js

My original question:

does javascript have an equivalent to the php magic class __call

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Gregg Lind
Solution 3
Solution 4 Matt
Solution 5