Search code examples
c#jsonwebmethod

No mapping exists from object type c#


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [WebMethod]
    public static string SaveLayout(string layout, object state)
    {



        SqlConnection conn = new SqlConnection(@"Persist Security Info=False;User ID=admin;Password=admin123;Initial Catalog=Test_Layout;Data Source=Myserver");
        conn.Open();
        SqlCommand cmd = new SqlCommand("insertlayout", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@layout", layout);
        cmd.Parameters.AddWithValue("@states", state);

        cmd.ExecuteNonQuery();
        conn.Close();
        return "successfully state saved";
    }
}

i am using webmethod(using Json,jquery) to store object in sql server 2008 but i am getting following error on sql server 2008 i am using varchar(max) datatype for storing object(state variable) in database how to convert state variable(object) to string to store in database

enter image description here

enter image description here


Solution

  • The problem is that you have to pass a string instead of dictionary. I may suggest you to serialise your dictionary and pass that value to AddWithValue function. Let JSON be the format of serialisation. I would recommend Json.net as serialization library. It provides convenient way of dictionary serialization/deserialization.

    So your code may look like this:

    cmd.Parameters.AddWithValue("@states", JsonConvert.SerializeObject(state));
    

    P.S. better use using statement both for SqlConnection and SqlCommand objects.