.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan
Post New Web Links

Sending JSON Array to an ASP.NET MVC Action Method Argument

Posted By:      Posted Date: October 04, 2010    Points: 0   Category :ASP.Net
 


 <input type = "submit" onclick = "savePayment()"  value = "Test"/>

    <script type="text/javascript">
        function savePayment() {
            //Creating some test data
            var lineItems = new Object();
            lineItems.Entrys = new Array();
            lineItems.Entrys[0] = new Object({ Name: "Dung", Age: "21"});
            lineItems.Entrys[1] = new Object({ Name: "An", Age: "25" });

            //Posting them to server with ajax
            $.ajax({
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                url: '<%=Url.Action("TestArray", "Json") %>',
                dataType: 'json',
                data: $.toJSON(lineItems),
                success: function (result) {
                    if (result) {
                        alert('Success');
                    }
                    else {
                        alert('Failure');
                    }
                }
            });
        }
</script>






View Complete Post


More Related Resource Links

Action method returning an ActionResult used in a Action method

  

Hell all,

I have the Index action method calling a method that itself is an action method.


Example :

public ActionResult Index()
{
   //do stuff
   ActionResult result = MethodB();
  
   // ?? what to return here ??
}

public ActionResult MethodB()
{
   //do stuff

  return View("Index);
}

What to do in this case ?


How to Pass higher Length of Byte Array to the remoting method

  
Dear all,I am using a windows application and the businness logic is present in the remote server.Once particular method takes bytearray as input parameter...Whenever the method call is made the function returns value .This is limited for the particular bytearray length. (4109228 bytes).If the length of bytearray crosses 4109228 bytes.I am getting an error that "input stream is not valid binary format".How to Pass higher Length of Byte Array to the remoting method... Greater than 4 MB?I believe something is missing in web.config or app.config...?What could be the issue...? Any sugesstions are welcome....ThanksRavikumar

Sending Array of Custom Class over WCF Problem

  
I have been attempting to convert some service calls that returned a DataSet into something more lightweight. For instance, I am converting: [OperationContract] public DataSet GetCommittees(); into: [OperationContract] public List<VolunteerCommittee> GetCommittees(); where committee is defined as: [DataContract] public class VolunteerCommittee { [DataMember] public int Id { get; set; } [DataMember] public String Name { get; set; } } I copied the structure of the data contract and the operation contract right from an example in a book I bought on WCF. The author mentioned that the List<VolunteerCommittee> would get converted into an array over the wire, so the client's operation contract looks like: [OperationContract] public VolunteerCommittee[] GetCommittees(); My problem: When the service is called, an empty array is returned every time. When I put trace statements in, I see an array of 48 VolunteerCommittees leaving the server. I've done some reading on the problem and tried a number of suggestions, such as using the XmlSerializer attribute, including a certain namespace as a [return:] on the server's contract, changing the type of binding (it's using wsHttpBinding... I tried basicHttpBinding) and turning off MTOM in the behavior, but none of these changed the empty result of the call. At this point, I'm hoping someone can shine some light on

passing multidementional array as paramater in method

  
hii want to pass multidementional array as parameter, below the code i worked, is it rightclass ASRateContract    {        public string[,] standardrate = new string[3,2];        public string[,] storagerate = new string[3,3];        public void  setstandardrate( string [3,2]name  )        {            standardrate = name;                   }        public string setstoragerate()        {            return "";        }        public string getstandardrate()        {                 return standardrate;        }

Sending JSON to an ASP.NET MVC

  
Hello all,I have problem with JSON, MapRoute.  If I click on "save" I always get Page / Index Page instead of / SendForm. I dont know why, in javascript it says url: '/ page / sendform'. But the problem is at Global.asax.cs, routes.MapRoute("Default",                "{controller}/{action}/{url}",                new { controller = "Page", action = "Index", url = UrlParameter.Optional });But there is still problem at the url, which shows Controller, Action that I dont want to .. I have a url / lang / seo-url / ..How can I achieve by clicking on the Save, it should call SendForm method instead of Index ..Thank you for your advice.Global.asax.cspublic class MvcApplication : System.Web.HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute("page", "{lang}/{url}", new { controller = "Page", action = "Index", lang = "cz", url = UrlParameter.Optional }); routes.MapRoute("Default", "{control

MVC - Return Array Json

  
  function SaveDataToArray1(VungNguyenLieu, DienTich,LoaiGiong,
                                 SanLuong, TGXuongGiong, TGThuHoach) 
        {
            var arr = new Array(arrData.length,
                                VungNguyenLieu, DienTich,LoaiGiong,
                                 SanLuong, TGXuongGiong, TGThuHoach);
            arrData1.push(arr);
            ReloadGrid1();
        }

        function ReloadGrid1() {
            $('#tbNoiDung tbody').html("");
            for (i = 0; i < arrData1.length; i++) {
                var tbRow = "<tr>";
                tbRow += "<td align=\"center\">" + (i + 1) + "</td>";
                tbRow += "<td align=\"center\">" + arrData[i][1] + "</td>";
                tbRow += "<td align=\"center\">" + arrData[i][2] + "</td>";
                tbRow += "<td align=\"center\">" + arrData[i][3] + "</td>";
                tbRow += "<td align=\"center\">" + arrData[i][4] + "</td>";
                tbRow += "<td align=\"center\">" + arrData[i][5] + "</td>";
                tbRow += "<td align=\"center\"

Accepting a Json in a controler method

  

I have a JSON object in javascript

it is a collection of Object

How can I pass this object to a controller if i am  submitting the form like

$('#myform').submit();

what object  type should i give for the parameter to accept this Json


Deserializing a JSON array of mixed types

  

Hi,

I'm having trouble deserializing a JSON array of mixed types using the DataContractJsonSerializer class. I've spent a bunch of time looking for a solution to no avail, so I thought I'd go ahead and ask here.

Basically, I am getting a JSON string like the one below. I'd like to get the array to deserialize into an List where position 0 has an Int32, position 1 has a String, and position 2 has an instance of my custom class.

[
   
2,
   
"Mr. Smith",
   
{
     
"num":169,
     
"name":"main street",
     
"state":66

How can I pass a NULL value as [in,out] argument to a COM method using late binding?

  

Suppose I have the following method in a COM interface defined in a C++ IDL:

[id(8)] HRESULT MyMethod([in,out,defaultvalue(NULL)] LONG* value, [out, retval] BSTR* returnValue);

Now I want to call this method passing in NULL for the 'value' parameter using late binding in C#. How can this be accomplished?

The following works if I want to pass a non-null argument as value:

         Type type = Type.GetTypeFromCLSID(new Guid("{7DA7BD6A-3E11-4E6B-BDE3-7C968A085F94}"));
         object instance = Activator.CreateInstance(type);

         object[] arguments = new object[] { 101 };

         ParameterModifier modifier = new ParameterModifier(1);

         modifier[0] = true;

         type.InvokeMember("[DispID=8]", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, instance, arguments, new ParameterModifier[] { modifier }, null, null);

         Console.WriteLine("Value after call: {0}", arguments[0]);

But how can I pass NULL? Using 'null' or Type.Missing give me type

What is the best method of sending through e-mail and error that is caught with the try, catch, etc

  

Using VB, VS 2010,  I am wanting a remote web app to send me an e-mail when it finds an error using the try catch.  What is the best way to do that?


JSON AJAX WCF SERVER METHOD FAILED 404

  

Hi guys

Am having a hard time trying to make my wcf work in asp.net ajax.

I have my service hosted on another machine: https://mydomain.com.au/myservice/json

I am calling the service from my http://localhost/default.aspx

When i call it it keeps returning me the error saying server method "MyMethod" failed and status code is 404

 

Here's my service setup.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
	<title></title>
	<script language="javascript" type="text/javascript">

		function Suceeded(msg) {
			alert("completed");
			// Do something with the response data here.
			//  Expect it to consistently have no .d.
		}

		function Failed(msg) {
			alert("failed");
			// Do something with the response data here.
			//  Expect it to consistently have no .d.
		}

		function CallWCFTwo() {
			var proxy = new tempuri.org.IAustPostService();
			var hellp = proxy.Ping(Suceeded, Failed, null);
		}

		function CallWCFThree() {
			var proxy = new tempuri.org.IMyService();
			var hellp = proxy.MyMethod("value 1", "value 2", Suceeded, Fa

Creating a One-Dimensional Array for use with AddUsersToRoles Method

  

Dear All

I've created an Excel spreadsheet for my users to upload into my web application to bulk import  memberships and roles into the application. There are up to 4 different roles which users can be members of so I'm using AddUsersToRoles to add the user to one or more roles in one line of code like this:

r.AddUsersToRoles(usernames, CreateListOfRoles(Role1, Role2, Role3, Role4))

As this line of code expects a one-dimensional array of roles, I have created a function to take in the roles from my spreadsheet, add them into a one-dimensional array, and return that to the AddUsersToRoles method. The CreateListOfRoles function looks like this:

    Function CreateListOfRoles(ByVal Role1 As String, ByVal Role2 As String, ByVal Role3 As String, ByVal Role4 As String) As Array

        Dim ar As New ArrayList

        'If the role boxes are not blank, add them to the array
        If Not String.IsNullOrEmpty(Role1) Then
            ar.Add(Role1)
        End If

        If Not String.IsNullOrEmpty(Role2) Then
            ar.Add(Role2)
        End If

        If Not String.IsNullOrEmpty(Role3) Then
            ar.Add(Role3)
        End If

        If Not String.IsNullOrEmpty(Role4) Then
            ar.Add(Role4)
        End If

        '

SharePoint Designer: Sending parameters with "Navigate to Page" form action

  
I want to create a custom button in my SharePoint form that uses Form Actions that commit the changes in the fields and then navigate to a designated page.  This works very well.

Then I want to send a parameter with the URL, for example: http://.../customform.aspx?ID={@ID}.  SharePoint Designer offers this option, but I have not been able to make it work.  Every time it just sends the literal {@ID} instead of it's content.

Has anyone solved this issue?

view the modelstate errors in action method

  

for debugging purposes, how do I see the ModelState errors from code in the action method?  ModelState.IsValid returns false. I want to copy the error messages to a variable so I can display them in the debugger.

thanks,

 


passing values to object properties of action method parameter

  

I have an action method that accepts a single parm.

That parm is an object with multiple properties. MVC correctly maps values from the querystring
to properties in the parm object by matching property name to querystring value name. 
Problem is, properties in the action method parm object which are themselves objects with
properties, are not assigned their matching values from the querystring. The class object has a
constructor which accepts a single string parameter.

How do I assign to properties of an action method parameter which are themselves class objects?

thanks,

 

                <%: Html.ActionLink("Edit", "ProductMasterEdit", 
                       new { ProdKey=item.ProductKey.Value, 
                       ProductKey = item.ProductKey.Value })%> 

    public ViewResult ProductMasterEdit(ProductMaster Item)
    {
  ...
   }

  public partial class ProductMaster
  {


    public ProductKey ProductKey
    {
      get { return new ProductKey(this.ProdKey); }
      set { this.ProdKey = value.Value; }
    }
}


 


jQuery post to an action method

  


Hi


I hope this is the right section to post this, as it does seem to be an MVC related issue. I'm trying to use the jQuery.post() function to post an object to an action method, but for some reason the nested objects aren't initialised properly when they're received by the action method.


Here's my javascript code:


var data = {
    Id: 10,
    User: {
        Id: 5
    }
};
$.post("/Home/SaveCompany", data, function (data) {
    alert("success");
});


And my action method:


[HttpPost]
public ActionResult SaveCompany(Company company)
{
    if (company.Id > 0) {
        _companyRepository.UpdateCompany(company);
    } else {
        _companyRepository.CreateCompany(company);
    }
    return Json(new { id = company.Id });
}


company.Id has a value of 10, but company.User.Id is 0. Any ideas what I'm doing wrong? I've not named any properties incorrectly, by the way.


Thanks


json array

  

i am new to json array... i cant understand one bit of this concept

i am pasting a code here. can any1  explain me this code


if (Request.QueryString["Tab"] == "Overview")
            {
                sReturnVal = "{\"array_list\":{\"list\":[";
                sReturnVal += "{\"Source\":'" + Request.QueryString["Tab"] + "'}]";
                string strVal = "";
Categories: 
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend