I created web service in visual studio 2010 three years back. I use this Web service in my winform project for performing some online functions. Now I want to create web service in visual studio 2013. Here I see web api instead of traditional web service. So my question is that what is the difference between traditional web service and Web api? And can I achieve the same thing in web api which I do in traditional web service?

I have a Web API setup and I want to pass a string parameter to the GetAutomation method. In Global.asax I have:

protected void Application_Start(object sender, EventArgs e)
    {
        RouteTable.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{testName}",
            defaults: new { id = System.Web.Http.RouteParameter.Optional });
        RouteTable.Routes.MapHttpRoute(
            name: "DefaultApiWithAction",
            routeTemplate: "api/{controller}/{action}/{testName}");
    }

In my AutomationController.cs, I have:

[ActionName("GetAutomation")]
    [HttpGet]
    public string StartAutomation(string testName)
    {
        //string testName = "MyTest123";
        Vmware.StartAutomation("automation-server", testName);
        return "Automation started for " + testName;
    }

If I remove the testName parameter from StartAutomation and call:

http://localhost/api/Automation/GetAutomation

it works. If I put it back in and try

http://localhost/api/Automation/GetAutomation/Test123

it fails with a 404 error. Any idea what I''m doing wrong? Thanks, J.

I've been trying to get DropDownListFor working in ASP.NET MVC using values from another table to link the model to the option selected. Full disclosure, I have very little idea what I'm doing and just working off examples.

Creating the DropDownList as follows:

@Html.DropDownListFor(model => model.GenreId, (SelectList)ViewBag.GenreSelect, new { @class = "form-control" })

GenreId is a column in the model's table.

I get the error:

An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code

Additional information: There is no ViewData item of type 'IEnumerable' that has the key 'GenreId'

ViewBag set like this before going to the view: (Id and name are columns in the Genre table)

private void SetGenreViewBag(int? GenreId= null)
    {
        if (GenreId== null)

            ViewBag.GenreSelect= new SelectList(db.Genres, "Id", "name");

        else

            ViewBag.GenreSelect = new SelectList(db.Genres, "Id", "name", GenreId);

    }

The model has a column for the Id of the genre.

I think my main problem is I don't understand the syntax of the DropDownListFor function, plus there's a dozen different overloads for it so it's hard to decipher. What is the purpose of the first parameter with the lambda? It seems to be taking the value you specify from the select list values, but I don't get how this connects to the model. Haven't found a clear answer online.

I thought I had this working, but something I did made it stop working. I also had it working before that with DropDownList() but I saw that DropDownListFor would be a bit better plus I couldn't get the HTML attributes working properly in DropDownList().

Thank you!

EDIT: Inside controller:

    public ActionResult Create()
    {
        SetGenreViewBag();
        return View();
    }

NOTE: The dropdown list shows all the right items (i.e. genres) but it crashes when I save the form.

// POST: Home/Create
    [HttpPost]
    public ActionResult Create(Song songToCreate)
    {
        try
        {
            db.Songs.Add(songToCreate);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

Song model:

namespace MyModule.Models
{
using System;
using System.Collections.Generic;

public partial class Song
    {
        public int Id { get; set; }
        public string name { get; set; }
        public int genreId { get; set; }
    }
}

I used this code to send push notification and it works well. Now i'm trying to send a notification to multiple devices, but im unable to do it, im getting "400 Bad Request Error".

Here is my modified code:

Shared Function sendPush(ByVal value As String) As String

        Dim toret As String = ""


        Dim regid As String = "[""XXXXXX"",""ZZZZZZ""]"

        Dim applicationID = "YYYYYYY"
        Dim SENDER_ID = "SSSSSSS"

        Dim tRequest As WebRequest
        tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send")
        tRequest.Method = "post"
        tRequest.ContentType = " application/json"
        tRequest.Headers.Add(String.Format("Authorization: key={0}", applicationID))

        tRequest.Headers.Add(String.Format("Sender: id={0}", SENDER_ID))

        Dim postData As String = "{""collapse_key"":""score_update"",""time_to_live"":108,""delay_while_idle"":1,""data"":{""message"":""" & Convert.ToString(value) & """,""time"":""" & System.DateTime.Now.ToString() & """},""registration_ids"":" & regid & "}"
        Console.WriteLine(postData)
        Dim byteArray As [Byte]() = Encoding.UTF8.GetBytes(postData)
        tRequest.ContentLength = byteArray.Length

        Dim dataStream As Stream = tRequest.GetRequestStream()
        dataStream.Write(byteArray, 0, byteArray.Length)
        dataStream.Close()

        Dim tResponse As WebResponse = tRequest.GetResponse()

        dataStream = tResponse.GetResponseStream()

        Dim tReader As New StreamReader(dataStream)

        Dim sResponseFromServer As [String] = tReader.ReadToEnd()

        toret = sResponseFromServer
        tReader.Close()
        dataStream.Close()
        tResponse.Close()

        Return toret
    End Function

I have a field on a user profile that corresponds to an id in another system. I want to set this when a user visits an activation link. After registering the user in the other system, I add a role and set their membership approval to true. I was getting an error saying that I cannot set the property of an anonymous user so I moved where I was assigning the id after the role/activation piece however I still got the same error.

private bool SetCustomId(string username, Guid id)
{

    var userProfile = ((User)User.FromName(username, AccountType.User)).Profile;
    userProfile.SetCustomProperty("MyIdField", id.ToString());
    userProfile.Save();//error thrown here
}

User profile is what I would expect and when I moved it after the piece that assigned the user a role, they did have the role I expected them to.

Here's the actual exception: This property cannot be set for anonymous users.

Background

I'm troubleshooting some issues with a .NET Web API 2 service. The issues are inconsistent, and from the requesting service, all we see are Connection Resets and Socket Exceptions. It is not even hitting the User Code/logging in the API, but for low level exceptions that doesn't rule the WEB API, or the box it's hosted on, out as the culprit.

Research

A very useful tool in the past for troubleshooting similar issues in WCF was enabling WCF Tracing. I'm looking for an equivalent that can show the low level Service Trace for the Web API.

I've found Global Error Handling and I've used packages like Elmah in the past. but to my knowledge this only shows unhandled exceptions, as opposed to the entire trace of the Service like the svclog does.

I also know about Fiddler and Wireshark, and while these are excellent tools for http tracking and low level protocol sniffing, I'm interested more in what the .NET service thinks it's receiving and how it's processing those actions, at this point rather than if packets are making it over the wire.

Summary

Is there an equivalent for Web API 2 to WCF .svclog? With particular focus on the low level service interactions with bytes/requests.

I have this:

<asp:DropDownList ID="DDL_Position" runat="server">
   <asp:ListItem Value="1"></asp:ListItem>
   <asp:ListItem Value="2"></asp:ListItem>
   <asp:ListItem Value="3"></asp:ListItem>
</asp:DropDownList>

I want to put images (40x40 px) instead of text as values. I tried different ways and none of them worked: Somewhere they advice to use code like:

<asp:ListItem Value="3" Text='<img src="images/photo.jpg" />'></asp:ListItem>

but obviously it did HTML encode and it displayed

"<img src="images/photo.jpg" />" 

as Option. I also tried

DDL_Position.Items[i].Attributes.Add("style", "background-image: url(image); background-repeat:no-repeat;

but I don't like the effect and it shows the images only when the ddl is clicked for the options, the selected option's image is not displayed and the ddl looks empty.

I am trying to programmatically list users in a Active Directory group using C#. Here are the SO posts I found:

How can I get a list of users from active directory?
How to get the groups of a user in Active Directory? (c#, asp.net)

I wrote a program that took inspiration from this post: http://stackoverflow.com/a/7242782

string name, container, user, pass;

System.IO.StreamReader file =
    new System.IO.StreamReader(@".\config.txt");

name = file.ReadLine();
container = file.ReadLine();
user = file.ReadLine();
pass = file.ReadLine();


try
{
    //PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "ad.domain.com",
    //    "OU=Group,DC=AD,DC=Domain,DC=COM",
    //    "domain\\user", "XXXXXX");
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain, name, container, ContextOptions.Negotiate ,user, pass);

    Console.Write("Enter Group: ");
    string group = Console.ReadLine();
    while (!String.IsNullOrEmpty(group))
    {
        // find the group in question
        GroupPrincipal gp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, group);

        // if found....
        if (gp != null)
        {
            // iterate over members
            foreach (Principal p in gp.GetMembers())
            {
                Console.WriteLine("{0}: {1}, {2}, {3}", p.StructuralObjectClass, p.DisplayName, p.SamAccountName, p.UserPrincipalName);
            }
        }

        //get next group
        Console.Write("Enter Group: ");
        group = Console.ReadLine();
    }

}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}

The exact scenario is this. There are two domains, domain A and domain B. Domain B has a one way trust to domain A.

I am connecting to domain B with a domain B credential and want to get a list of users in a domain local group which contains users of domain A and domain B. Using the above code, when I query a global or universal group in Domain B, everything works fine. However when I try and query a domain local group in Domain B, I get the following output:

Enter Group: global group
user: XXX, XXX, XXX@XXX.com
Enter Group: domain local group
System.Security.Authentication.AuthenticationException: The user name or password is incorrect.
 ---> System.Runtime.InteropServices.COMException: The user name or password is incorrect.

   at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
   at System.DirectoryServices.DirectoryEntry.Bind()
   at System.DirectoryServices.DirectoryEntry.get_AdsObject()
   at System.DirectoryServices.PropertyValueCollection.PopulateList()
   at System.DirectoryServices.PropertyValueCollection..ctor(DirectoryEntry entry, String propertyName)
   at System.DirectoryServices.PropertyCollection.get_Item(String propertyName)
   at System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInitNoContainer()
   at System.DirectoryServices.AccountManagement.PrincipalContext.DoDomainInit()
   at System.DirectoryServices.AccountManagement.PrincipalContext.Initialize()
   at System.DirectoryServices.AccountManagement.PrincipalContext.get_QueryCtx()
   at System.DirectoryServices.AccountManagement.ADStoreCtx.ResolveCrossStoreRefToPrincipal(Object o)
   --- End of inner exception stack trace ---
   at System.DirectoryServices.AccountManagement.ADStoreCtx.ResolveCrossStoreRefToPrincipal(Object o)
   at System.DirectoryServices.AccountManagement.ADUtils.DirectoryEntryAsPrincipal(DirectoryEntry de, ADStoreCtx storeCtx)
   at System.DirectoryServices.AccountManagement.ADDNLinkedAttrSet.get_CurrentAsPrincipal()
   at System.DirectoryServices.AccountManagement.FindResultEnumerator`1.get_Current()
   at ADGroupListTest.Program.Main(String[] args)

When I connect to Domain B with Domain A credentials i get the following output (once again, global and universal groups work fine but domain local groups dont):

Enter Group: global group
user: XXX, XXX, XXX@XXX.com
Enter Group: domain local group
System.DirectoryServices.AccountManagement.PrincipalOperationException: The specified directory service attribute or value does not exist.
 ---> System.Runtime.InteropServices.COMException: The specified directory service attribute or value does not exist.

   at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
   at System.DirectoryServices.DirectoryEntry.Bind()
   at System.DirectoryServices.DirectoryEntry.get_SchemaEntry()
   at System.DirectoryServices.AccountManagement.ADStoreCtx.IsContainer(DirectoryEntry de)
   at System.DirectoryServices.AccountManagement.ADStoreCtx..ctor(DirectoryEntry ctxBase, Boolean ownCtxBase, String username, String password, ContextOptions options)
   at System.DirectoryServices.AccountManagement.PrincipalContext.CreateContextFromDirectoryEntry(DirectoryEntry entry)
   at System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInitNoContainer()
   at System.DirectoryServices.AccountManagement.PrincipalContext.DoDomainInit()
   at System.DirectoryServices.AccountManagement.PrincipalContext.Initialize()
   at System.DirectoryServices.AccountManagement.PrincipalContext.get_QueryCtx()
   at System.DirectoryServices.AccountManagement.ADStoreCtx.ResolveCrossStoreRefToPrincipal(Object o)
   --- End of inner exception stack trace ---
   at System.DirectoryServices.AccountManagement.ADStoreCtx.ResolveCrossStoreRefToPrincipal(Object o)
   at System.DirectoryServices.AccountManagement.ADUtils.DirectoryEntryAsPrincipal(DirectoryEntry de, ADStoreCtx storeCtx)
   at System.DirectoryServices.AccountManagement.ADDNLinkedAttrSet.get_CurrentAsPrincipal()
   at System.DirectoryServices.AccountManagement.FindResultEnumerator`1.get_Current()
   at ADGroupListTest.Program.Main(String[] args)

Is it possible to list domain local groups when logging in with domain B credentials? If so, how?
Is it possible to list domain local groups when logging in with domain A credentials? If so, how?

Thanks!

Basically i have a table with a lot of activities, each activity has a sport , and i want to link the name of the activity (that is also the name of the name of the sport which the activity is associated to) to the correspondent sport page, and i am getting the following error:

undefined method `model_name' for Sport::ActiveRecord_Relation:Class

The view here i get the error:

<% @activity.each do |activity| %>
<tr>
<td><%= link_to activity.id, activity_path(activity) %></td>
<td><%= link_to activity.name, searchsport(activity.name) %></td> //error here//
<td><%= activity.ambiente %></td>
<td><%= activity.resume %></td>
<td><%= activity.duration %></td>

I have this helper method in the controller:

  helper_method :searchsport
  def searchsport(name)
    Sport.where(:name => name)
  end

Sports table:

  create_table "sports", force: true do |t|
    t.string   "name"
    t.string   "description"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

I have MVC4 + EF5 app with single connectionString in web.config, and single DBContext using it.

I have a simply Create controller.

I have successfully ran my app in DEV.

I am attempting to move to UAT, which involved new DB, so I updated the connectionString, and on SaveChanges() I get a DBUpdate exception like:

{"Invalid object name 'DBNAME.dbo.TABLENAME'."}

where DBNAME is my DEV database name. Yet I can see that the connection is being made to correct SQL Server instance. All my AJAX/JSON form methods are connecting to the DB just fine.. it is only when I go to save the form that I get the issue of EF trying to look for wrong DB on correct SQL Server.

If i modify the destination table in such a way that it doesn't fit my model, on SaveChanges() I will instead get exception complaining of the mismatch... so seems like only when the target schema is correct, for some reason EF is falling back to my DEV DB name.

Where could the old DB name be cached? There's no reference to it anywhere now. How can I 'reset' this?

EDIT:Forgot to mention I'm using Code First, but the schema already exists.. i just have manually written the model classes, without using DatabaseMigrations.

(sorry for lazy phrasing--i've been at this forever and am getting tired and frustrated)

This is in a MVC 4 app. Code looks as follows:

<div id="example">
    
        @if (Model.Questionnaires != null && Model.Questionnaires.Count > 0)
        {
            foreach (var item in Model.Questionnaires)
            {
                @Html.Label(@item.Title)  
                <div class="demo-section">
                    @foreach (var question in item.Questions)
                    {
                        <label id="@question.QuestionId.ToString()">@question.Text</label> <br />
                        @Html.Label(@question.Text ) <br />
                    }
                </div>
                <br />
            }
        }
        else 
        {
            <p>No matching lists where found.</p>
        }
    
</div>

The resulting output look like this:

<div id="example">

  <label for="Pharmacy_Technician">Pharmacy Technician</label>
  <div class="demo-section">
    <label id="e4a2a2c9-2647-674e-b9fa-ff0000785e25">At least 18 years of age</label>
    <br />
    <label for="At_least_18_years_of_age">At least 18 years of age</label>
    <br />
    <label id="16a3a2c9-2647-674e-b9fa-ff0000785e25">Have a high school diploma or GED</label>
    <br />
    <label for="Have_a_high_school_diploma_or_GED">Have a high school diploma or GED</label>
    <br />
    <label id="24a3a2c9-2647-674e-b9fa-ff0000785e25">Have completed a training program or have a minimum 12 months of pharmacy related experience within the last 36 months</label>
    <br />
    <label for="Have_completed_a_training_program_or_have_a_minimum_12_months_of_pharmacy_related_experience_within_the_last_36_months">Have completed a training program or have a minimum 12 months of pharmacy related experience within the last 36 months</label>
    <br />
  </div>
  <br />
  <label for="Phlebotomy_Technician">Phlebotomy Technician</label>
  <div class="demo-section">
    <label id="afa5a2c9-2647-674e-b9fa-ff0000785e25">* Have successfully completed a training program or one year of work experience within the field. There is no specific time frame a candidate must test within once the training or work experience eligibility requirement has been met.</label>
    <br />
    <label for=""></label>
    <br />
    <label id="68a5a2c9-2647-674e-b9fa-ff0000785e25">* Posess a High School Diploma, or the equivalent</label>
    <br />
    <label for="">* Posess a High School Diploma, or the equivalent</label>
    <br />
  </div>
  <br />

</div>


</div>

As you can see there is a blank label that the helper is creating. I do not understand why the Helper is killing the value of the label text.

The other thing that I do not understand is why the for is being populate in the first set of question why the second one is empty.

I am making a small project using jQuery, MVC4 with Razon and C#. In my view I have a drop down list and I wish to give it the attribute of data-url=Url.Action("UpdateDeliveryAddress", "Home"):

<div class="@dropDownListClass">
    @Html.DropDownList("theList", null, new {data-url=Url.Action("UpdateDeliveryAddress", "Home") })
</div>

However, when I do so, I get the follow error:

invalid anonymous type member declarator anonymous type members must be declared with a member assignemnt, simple name or member access.

What am I missing? Why do I have this error?

I have two tables - ContactInformation & EmailAddress - which have a many to many (* : *) relationship. After making this association in the ADO.NET data model and generate the db from it, a table titled ContactInformationEmailAddresses which maps the two tables is created in the Entities Container.

Unlike when I scaffold views which have a 1:* relationship, there's no entries available for its counterpart in the view when I scaffold either one and scaffolding off the combined table isn't an option even after updating the model from the db.

My question is simply: is there an automated way to generate the creation form for ContactInformationEmailAddresses that will have the EmailAddress entry field?

I have an markup

            <div id="uploadControl" class="fileUpload1">
                    <label for="uploadFile" id="labelId">Choose File</label>
                    <input class="upload" type="file" id="uploadFile" />
                </div>

javascript

        window.onload = function () {
    document.getElementById('uploadControl').onclick = function (event) {

        // process the event only for the original source 
        if (window.event.srcElement.id === 'uploadControl') {
            document.getElementById('labelId').click();
        }
        //prevent event propagation
        window.event.cancelBubble = true;
    };
}

I want to the label to fire a click event for the input File whenever the "upload control" div is clicked. The problem is.... this works on IE and chrome but on firefox i get the message
"TypeError: window.event is undefined "
It seems like firefox doesnt support window.event code. How can i make it work on firefox? please help

I am trying to obtain the return of a Javascript function that I call ont server side using ScriptManager.RegisterClientScriptBlock .

Currently, my javascript function save the value in a HiddenField that is contained in an UpdatePanel. When I call the method , I run the ScriptManager.RegisterClientScriptBlock and after that get the value of the HiddenField , but always returns me the value of the previous call. Here I show the code:

My User Control ASPX Side:

<script>

var num = 0;

function getReturn() {

    num = num + 1;
    var hr= document.getElementById('<%= hdf.ClientID %>');
    hRetorno.value = num;

}
</script>

...

<asp:UpdatePanel ID="up1" UpdateMode="Conditional" runat="server">
    <ContentTemplate>
        <asp:HiddenField ID="hdf" runat="server" />
    </ContentTemplate>
</asp:UpdatePanel>

My User Control Server Side Code:

    public String GetReturn()
    {
        return MyControl.jsGetReturn(this.Page, this.hdf);
    }

    private static String jsGetReturn(Page page, HiddenField hid)
    {
        ScriptManager.RegisterStartupScript(page, page.GetType(), "key", "getReturn();", true);

        return hid.Value;

    }

Index Page ASPX Side:

        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>

        <div style="width:720px; height:480px;">
            <uc1:MyControl runat="server" id="MyControl1"/>
        </div>

        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
            <ContentTemplate>

                <asp:Button ID="btn" runat="server" OnClick="btn_Click" />
                <asp:TextBox ID="txt" runat="server" ></asp:TextBox>

            </ContentTemplate>
        </asp:UpdatePanel>

Index Page Server Side Code:

    protected void btn_Click(object sender, EventArgs e)
    {
        txt.Text = MyControl1.GetReturn();
    }

I have built up a database structure that works with entities as general pieces of content for the site. This includes pages, articles and the different content types one could imagine.

Now foreach type of entity i want to have a different url, like "/page/xy" or "/article/xy", without having to setup a page controller or an article controller.

So my question in short is: How to implement dynamic content types? I can not write an mvc-bundle foreach url, because I don't know beforehand which types might come!

My approach in raw PHP would be to create an index.php file that reads out the current url and searches in the database for an entity type with the given name of the first segment in the url. if there is an entity type with that name, it shall print a list with entities that are of that type. Pretty easy in raw PHP, but how to do it in CakePHP?

What's the difference between MVC (Model View Controller) and BCE (Boundary Control Entity), I know that these two pattern are similar, but there's a difference, what is that difference?

I have site with couple kendo ui date pickers. When I view it on android/iphone phone I press the date field first. Keyboard is displayed, then I click on he calendar icon and the date look-up is displayed behind the keyboard. Is there a away to display the calendar look-up on top of keyboard?

All of my templates are working for non nullable value type. When the value type is a nullable though, Editor will use the template for strings instead.

This is my code:

Decimal.cshtml

@model Nullable<decimal>
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
        new { @class = "form-control validateFloat", placeholder = ViewData.ModelMetadata.Watermark })

Object.cshtml

@foreach (var prop in ViewData.ModelMetadata.Properties
    .Where(p => p.ShowForEdit)) {
    if ((prop.AdditionalValues.ContainsKey("DoNotAutoGenerate")) ||
        (string.IsNullOrEmpty(prop.DataTypeName) && prop.Model is IEnumerable<object>))
    {
        // Do not generate  
    } 
    else if (prop.TemplateHint == "HiddenInput")
    {
        @Html.Hidden(prop.PropertyName)
    }
    else
    {
        <div class="form-group">
            @Html.LabelLocalized(prop, ViewData.ModelMetadata, mgr)         
            <div class="col-md-10">
                @if(ViewData.ModelMetadata.IsPrimaryKey(prop))
                {
                    @Html.Editor(prop.PropertyName, "ReadOnly")
                }else
                {                    
                    @Html.Editor(prop.PropertyName, prop.DataTypeName) <-- This line calls String.cshtml instead of Decimal.cshtml when the data type is Nullable<decimal>. When the data type is decimal, the right template (Decimal.cshtml) is called.
                    @Html.ValidationMessage(prop.PropertyName)
                }
            </div>
        </div>
    } }

ProductDefinitionViewModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Infrastructure.Attributes;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using ERPInterface;
using System.Web.Mvc;
using InventoryInterface;

namespace WebUI.ViewModels
{
    public class ProductDefinitionViewModel
    {
        //public ProductDefinitionViewModel()
        //{
        //    AttachedProductDefinitions = new List<AttachedProductDefinition>();
        //    ReplacementProductDefinitions = new List<ReplacementProductDefinition>();
        //}

        [DataType("ReadOnly")]
        public int ProductDefinitionId { get; set; }
        public bool IsActive { get; set; }
        public Translation NameTranslation { get; set; }
        public string InternalId { get; set; }
        public string ExternalId { get; set; }

        [DataType("UnitOfMeasurementId")]
        public int UnitOfMeasurementId { get; set; }
        [DataType("Taxes")]
        public List<InventoryInterface.ProductDefinitionTax> ProductDefinitionTaxes { get; set; }

        [AdditionalMetadata("DoNotAutoGenerate", true)]
        public int NameTranslationId { get; set; }


        public ICollection<InventoryInterface.ProductDefinitionCode> ProductDefinitionCodes { get; set; }
        [DataType("ProductDefinitionNatures")]
        public Nullable<int> ProductDefinitionNatureId { get; set; }

        public bool FixedWeight { get; set; }
        public Nullable<decimal> Weight { get; set; } <-- Calls String template instead of Decimal template
        public Nullable<decimal> MinWeight { get; set; }
        public Nullable<decimal> MaxWeight { get; set; }
        public Nullable<decimal> PackagingWeight { get; set; }

        [DataType("Categories")]
        public Nullable<int> CategoryId { get; set; }
        [DataType("ProductDefinitionGroups")]
        public Nullable<int> ProductDefinitionGroupId { get; set; }   

        public List<AttachedProductDefinition> AttachedProductDefinitions { get; set; }
        public List<ReplacementProductDefinition> ReplacementProductDefinitions { get; set; }
    }
}

What is missing so that the function Editor calls the decimal template instead of the string template?

I am trying to do the following:

@Html.DropDownListFor(model => model.HPA, new SelectList(Categories.Types, "TupleId", "Name"), new { @class = "form-control" })

The model.HPA contains the following:

public List<HPADTO> HPAs { get; set; }

    public Tuple<int, int> HPA
    {
        get
        {
            // DO NOT USE.
            return Tuple.Create<int, int>(-1, -1);
        }
        set
        {
            var hPA = new HPADTO();
            hPA.PersonCategoryId = value.Item1;
            hPA.PersonId = value.Item2;
            HPAs.Add(hPA);
        }
    }

It is properly shown in the view:

<select id="id" class="form-control" name="HPA">
    <option value="(1, 1)"></option>
    <option value="(1, 5)"></option>
</select>

But it raises "NullReferenceException" after posting back as "value" in HPA.set is null.

Where is the error or how should I address this situation properly?

This is My View

@using(@Html.BeginForm("CrmBlogGroupType","knowledge",FormMethod.Get)){
       @Html.TextBox("search") 
         @Html.Hidden("type", (string)ViewBag.type)
           @Html.DropDownList("PageSize",
        new List<SelectListItem>()
        {
             new SelectListItem ()
        {
        Text="--Select Page Size--" ,Value="10",Selected=true
        },
        new SelectListItem ()
        {
        Text="View 20 records" ,Value="20"
        },
        new SelectListItem ()
        {
        Text="View 50 records" ,Value="50"
        },
          new SelectListItem ()
        {
        Text="View 100 records" ,Value="100"
        },
        })
           <input type="submit" value="search" id="Searchbtn" />
         <br />
           @Html.CheckBox("Name")<text>Author Name</text>
           @Html.CheckBox("AuthorTitle")<text>Title</text>
           @Html.CheckBox("Description")<text>Description</text>
       }

Here is the PagedList Code

@Html.PagedListPager(Model, page => Url.Action("CrmBlogGroupType", 
new     {page,Name=Request.QueryString["Name"].ToLower().Contains("true"),
AuthorTitle=Request.QueryString["AuthorTitle"].ToLower().Contains("true"),
Description=Request.QueryString["Description"].ToLower().Contains("true"),      search=Request.QueryString["search"],PageSize=Request.QueryString["PageSize"],type=Request.QueryStrin g["type"]}),new PagedListRenderOptions() 
{ 
   DisplayLinkToFirstPage=true,DisplayLinkToLastPage=true,DisplayPageCountAndCurrentLocation=true,Displa      yItemSliceAndTotal=true
    ,DisplayEllipsesWhenNotShowingAllPageNumbers=true,MaximumPageNumbersToDisplay=10
})

Controller Code

public ActionResult CrmBlogGroupType(int? page, bool? Name, bool? AuthorTitle, bool?Description, string search, int? PageSize, string type)
    {

        if (type==null)
        {
            //setting the Value in the initial call 
            //If the SP has changed then make the type parameter as the INT
            type = "A";
        }

        IEnumerable<Usp_getBlogSetPosts_Result> _objBlogSet = _dataLayer.GetBlogSet(type).ToList().ToPagedList(page ?? 1, PageSize ?? 10);
        return View(_objBlogSet);
        }

Getting an ERROR :

Object reference not set to an instance of an object.

Line 202:    @if (ViewBag.Search!=null && ViewBag.Search!=string.Empty)            
Line 203:{
Line 204:@Html.PagedListPager(Model, page => Url.Action("CrmBlogGroupType", new { page,
Line        205:Name=Request.QueryString["Name"].ToLower().Contains("true"),AuthorTitle=Request.QueryString["Auth    orTitle"].ToLower().Contains("true"),
Line 206:Description=Request.QueryString["Description"].ToLower().Contains("true"),

I've gone through some links by which i could make up the code like this, at last got stuck here Any help on this is highly appreciated..