Controller返回列表对象的类型名称,而不是列表中的内容

时间:2016-07-14 15:24:58

标签: c# asp.net-mvc

我有一个简单的代码,我试图从控制器方法返回列表对象并在浏览器上显示它。相反,浏览器将列表类型显示为:

System.Collections.Generic.List`1[System.String]

以下是我的代码:

控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using System.Web.Http;
using System.Web.Script.Serialization;
using MvcApplication2.Models;
using Newtonsoft.Json;

namespace MvcApplication2.Controllers
{
    public class CodesController : Controller
    {
        WebClient myclient = new WebClient();

        public IEnumerable<Codes> Get()
        {
            string data = myclient.DownloadString("URL");
            List<Codes> myobj = (List<Codes>)JsonConvert.DeserializeObject(data, typeof(List<Codes>));
            return myobj;
        }
    }
}

的DataModel:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication2.Models
{
    public class Codes
    {
        public string hr { get; set; }
        public string ps { get; set; }
    }
}

任何人都可以告诉我丢失的地方,我希望测试列表中的代码显示在浏览器上而不是System.Collections.Generic.List`1[System.String]类型。我对MVC很新,是否可以返回简单列表并从控制器在浏览器上呈现它而不是使用视图。

1 个答案:

答案 0 :(得分:5)

控制器操作不用于返回POCO对象。你最好返回一个继承自ActionResult的类的实例,它负责以所需的方式用HTML表示你的实际结果。

例如,如果要执行某些视图并呈现HTML,则应使用Controller.View方法,该方法返回ViewResult

目前尚不清楚您希望如何代表您的收藏品,但我想这可能是JSON。在这种情况下,您可以使用默认Controller.Json方法,或返回ActionResult ActionResult的实施。

如果你返回的内容不是从string继承的,asp.net mvc会尝试将其转换为ActionResult,并将转换后的字符串作为纯文本返回,不做任何修改。 some custom类的此方法负责处理您在操作中返回的内容。进一步的代码只适用于/// <summary>Creates the action result.</summary> /// <returns>The action result object.</returns> /// <param name="controllerContext">The controller context.</param> /// <param name="actionDescriptor">The action descriptor.</param> /// <param name="actionReturnValue">The action return value.</param> protected virtual ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue) { if (actionReturnValue == null) return new EmptyResult(); var actionResult = actionReturnValue as ActionResult; if (actionResult == null) { actionResult = new ContentResult() { Content = Convert.ToString(actionReturnValue, (IFormatProvider) CultureInfo.InvariantCulture) }; } return actionResult; } 个继承者,所以如果你不返回其中一个,它将被转换:

List

键入ToString不会覆盖System.Collections.Generic.List`1[System.String]方法,因此它的默认实现是返回完整类型名称。在您的情况下,它是public class CodesController : Controller { public ActionResult GetListJson() { var list = new List<string> { "AA", "BB", "CC" }; return this.Json(list , JsonRequestBehavior.AllowGet); } public ActionResult GetListText() { var list = new List<string> { "AA", "BB", "CC" }; return this.Content(string.Join(",", list)); } public ActionResult GetListView() { var list = new List<string> { "AA", "BB", "CC" }; return this.View(list); } }

尝试这样的事情:

["AA", "BB", "CC"]

第一种方法将返回 application / json AA,BB,CC

第二种方法将返回 text / plain GetListView.cshtml

第三种方法将返回 text / html ,但您必须创建名为@using System.Collections.Generic.List<string> <!DOCTYPE html> <html> <head> <title>page list</title> </head> <body> @foreach(var item in this.Model) { <p>@item</p> } </body> </html> 的视图:

[AA,BB],[AA,BB],[AA,BB]
根据您的评论

更新,您只想返回一些文字。见下面的代码。它将返回您想要的内容:public ActionResult Get() { string data = myclient.DownloadString("URL"); List<Codes> myobj = (List<Codes>)JsonConvert.DeserializeObject(data, typeof(List<Codes>)); // Let's convert it into what you want. var text = string.Join(",", list.Select(x => string.Format("[{0},{1}]", x.hr, x.ps))); return this.Content(text); } 。请注意结果类型和手动数据序列化的需要。

ActionResult

或者,您可以创建自己的public class CodesResult : ActionResult { private readonly List<Codes> _list; public CodesResult(List<Codes> list) { this._list = list; } public override void ExecuteResult(ControllerContext context) { if (context == null) throw new ArgumentNullException("context"); var response = context.HttpContext.Response; response.ContentType = "text/plain"; if (this._list != null) { // You still have to define serialization var text = string.Join(",", this._list.Select(x => string.Format("[{0},{1}]", x.hr, x.ps))); response.Write(text); } } }

public ActionResult Get()
{
    string data = myclient.DownloadString("URL");
    List<Codes> myobj = (List<Codes>)JsonConvert.DeserializeObject(data, typeof(List<Codes>));
    return new CodesResult(myobj);
}

然后使用它:

    package com.example.ermanager;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import com.example.ermanager.R.drawable;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Toast;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;

public class order extends Activity {
String text;
    private CheckBox chk;
        List<String> orderList = new ArrayList<String>();
        List<String> nameList = new ArrayList<String>();
        List<String> priceList = new ArrayList<String>();
        List<String> timeList = new ArrayList<String>();

        String wname=null;
         private AsyncTask<String, String, String> asyncTaskorder;


 private AsyncTask<String, String, String> asyncTask;
    private String response;
    private static Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_order);

     wname =waiter.getWaiter();

     Log.i("tag", "waiter name is "+wname);

     stopService(new Intent(getBaseContext(), notifcationService.class));

     GetDishesAsyncTask runner=new GetDishesAsyncTask();
    //dummy username and password just to avoid errors, no need
    String userName="a";
    String password="b";

    asyncTask=runner.execute(userName,password);
    String asyncResultText;
    try {
        asyncResultText = asyncTask.get();
          response = asyncResultText.trim();

          Log.i("tag", "dishes from server is "+response);

          //string prsing code started

          String name_string="";
        String price_string="";
        String time_string="";
        int name_counter=0;
        int price_counter=0;
        int time_counter=0;




        char [] ch_resp = response.toCharArray();


        //initial parsing for name sting...assining values to name_string

        for(int i=0; i<response.length(); i++)
        {

            if(ch_resp[i]=='*' && name_counter==0)
            {
                name_counter=1; 

            continue;
            }

            if(ch_resp[i]=='*' && name_counter==1)
            {
                break;
            }

            if(name_counter==1)
            {
                name_string=name_string+ch_resp[i];

            }

        }
        Log.i("tag", " first name array is "+name_string);


        //for price string

        response=response.replace("*"+name_string+"*", "");

        ch_resp = response.toCharArray();

        for(int i=0; i<response.length(); i++)
        {

            if(ch_resp[i]=='&' && price_counter==0)
            {
                price_counter=1;    

            continue;
            }

            if(ch_resp[i]=='&' && price_counter==1)
            {
                break;
            }

            if(price_counter==1)
            {
                price_string=price_string+ch_resp[i];

            }

        }

        Log.i("tag", " first lat array is "+price_string);




        response=response.replace("&"+price_string+"&", "");

        //initial parsing for time sting...assining values to time_string

        ch_resp = response.toCharArray();

        for(int i=0; i<response.length(); i++)
        {

            if(ch_resp[i]=='^' && time_counter==0)
            {
                time_counter=1; 

            continue;
            }

            if(ch_resp[i]=='^' && time_counter==1)
            {
                break;
            }

            if(time_counter==1)
            {
                time_string=time_string+ch_resp[i];

            }

        }

        Log.i("tag", " first longg array is "+time_string);

        String temp="";




        int count=0;

        char [] name_string1 = name_string.toCharArray();
        char [] price_string1 = price_string.toCharArray();
        char [] time_string1 = time_string.toCharArray();


        //***** parsing code for names

        char msg;

        // Log.i("tag", name_string);
         for(int i=0; i<name_string1.length; i++)
            {




                if(name_string1[i]==':')
                {
                    msg=name_string1[i];
                   Log.i("tag", "first time "+msg+" found");
                  // alert("first time "+name_string1[i]+" found");

                    for(int j=i+1; j<name_string1.length; j++)
                    {


                       // alert(" in j loop, j at "+name_string[j]);
                        if(name_string1[j]!=':')
                        {
                     // alert("in temp if");
                            temp=temp+name_string1[j];

                            Log.i("tag", "now temp is"+temp);
                        }

                        else if (name_string1[j]==':')
                        {   

                           msg=name_string1[j];
                     Log.i("tag", "else satisfied "+msg+" found");
                     Log.i("tag", "final name is "+temp);

                    nameList.add(temp);

                      Log.i("tag", "name list at count is"+nameList.get(count));
                       Log.i("tag", "count value is "+count);

                       //  alert("count at "+count+" and array is"+final_name_array[count]);
                            temp="";
                       count++;

                            i=j-1;
                            //alert(" name string of i is"+name_string[i]);
                            break;
                        }
                        }


                }

            }

         //***** parsing code for price
         count=0;


        // Log.i("tag", name_string);
         for(int i=0; i<price_string1.length; i++)
            {



                if(price_string1[i]==':')
                {
                    msg=price_string1[i];
                   Log.i("tag", "first time "+msg+" found");
                  // alert("first time "+name_string1[i]+" found");

                    for(int j=i+1; j<price_string1.length; j++)
                    {


                       // alert(" in j loop, j at "+name_string[j]);
                        if(price_string1[j]!=':')
                        {
                     // alert("in temp if");
                            temp=temp+price_string1[j];

                            Log.i("tag", "now temp is"+temp);
                        }

                        else if (price_string1[j]==':')
                        {   

                           msg=price_string1[j];
                     Log.i("tag", "else satisfied "+msg+" found");
                     Log.i("tag", "final name is "+temp);

                    priceList.add(temp);

                      Log.i("tag", "price list at count is "+priceList.get(count));
                       Log.i("tag", "count value is "+count);

                       //  alert("count at "+count+" and array is"+final_name_array[count]);
                            temp="";
                       count++;

                            i=j-1;
                            //alert(" name string of i is"+name_string[i]);
                            break;
                        }
                        }


                }

            }



         //******* parsing code for longg

         count=0;

         for(int i=0; i<time_string1.length; i++)
         {



             if(time_string1[i]==':')
             {
                 msg=time_string1[i];
               Log.i("tag", "first time "+msg+" found");
              // alert("first time "+name_string1[i]+" found");

                 for(int j=i+1; j<time_string1.length; j++)
                 {


                    // alert(" in j loop, j at "+name_string[j]);
                     if(time_string1[j]!=':')
                     {
                  // alert("in temp if");
                         temp=temp+time_string1[j];

                         Log.i("tag", "now temp is"+temp);
                     }

                     else if (time_string1[j]==':')
                     {   

                       msg=time_string1[j];
                  Log.i("tag", "else satisfied "+msg+" found");
                  Log.i("tag", "final name is "+temp);

                 timeList.add(temp);

                   Log.i("tag", "time list at count is "+timeList.get(count));
                    Log.i("tag", "count value is "+count);

                    //  alert("count at "+count+" and array is"+final_name_array[count]);
                         temp="";
                    count++;

                         i=j-1;
                         //alert(" name string of i is"+name_string[i]);
                         break;
                     }
                     }


             }

         }

         Log.i("tag", "******************************");

         for(String loop:nameList)
         {
            Log.i("tag", loop);
         }

         for(String loop:priceList)
            {


            Log.i("tag",  loop);
            }   


         for(String loop:timeList)
            {

            Log.i("tag", loop);
            }




    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }



    //ScrollView sv = new ScrollView(this);

    final View linearLayout =  findViewById(R.id.main_layout);
    //LinearLayout layout = (LinearLayout) findViewById(R.id.info);
    ((LinearLayout) linearLayout).setBackgroundResource(R.drawable.bg);
    //sv.addView(linearLayout);    //this is what i have tried
    for(int i=0; i<nameList.size(); i++)
    {
    TextView valueTV = new TextView(this);
    valueTV.setText(":Dish Name: "+nameList.get(i)+" Dish price: "+priceList.get(i)+" Dish time: "+timeList.get(i)+":");
    TextView valueTV1 = new TextView(this);
    valueTV1.setText(":"+nameList.get(i)+":"+priceList.get(i)+":"+timeList.get(i)+":");
    valueTV1.setVisibility(View.GONE);
   // sv.addView(linearLayout);
    chk=new CheckBox(this);
    chk.setId(i);
    chk.setText("Order");
    chk.setTextColor(Color.BLACK);
    Log.i("tag", " i is "+i+" id assigned to chk box is"+chk.getId());

    EditText quantity = new EditText(this);
    quantity.setHint("Quantity");


    valueTV1.setLayoutParams(new LayoutParams(android.app.ActionBar.LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
    ((LinearLayout) linearLayout).addView(valueTV);
    ((LinearLayout) linearLayout).addView(valueTV1);
    ((LinearLayout) linearLayout).addView(chk);
    ((LinearLayout) linearLayout).addView(quantity);

    }
    final EditText specialInstruction = new EditText(this);

    final EditText tableNo = new EditText(this);


    Button myButton = new Button(this);
    TextView tv1 = new TextView(this);
    ((LinearLayout) linearLayout).addView(tv1);
    specialInstruction.setGravity(Gravity.CENTER);
    specialInstruction.setHint("Special Instructions");
    ((LinearLayout) linearLayout).addView(specialInstruction);

    tableNo.setGravity(Gravity.CENTER);
    tableNo.setHint("Table No");
    ((LinearLayout) linearLayout).addView(tableNo);

    myButton.setText("Send Order");


    ((LinearLayout) linearLayout).addView(myButton);



    myButton.setOnClickListener(new OnClickListener() {

        @SuppressLint("ShowToast") @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            boolean oneChecked = false;
             v = null;

             Intent intent = getIntent();
             String quant = null;
             //String username = intent.getExtras().getString("username");
             //Log.i("tag", "username is"+username);
             Log.i("tag", "in Listener");
            for(int i=0; i<=(nameList.size()*4)-1; i++)
            {
                Log.i("tag", "in loop");

                //Log.i("tag", "in loop i is, "+i+" nameList size is "+nameList.size());                    
                    v = ((LinearLayout) linearLayout).getChildAt(i);
                    if (v instanceof CheckBox) {
                        if (((CheckBox) v).isChecked()) {
                            oneChecked = true;

                            if (oneChecked) {
                                Log.i("tag", "in checkbox");
                                Log.i("tag", " check box at "+i+" is checked");

                                 View v1;
                                 v1 = ((LinearLayout) linearLayout).getChildAt(i-1);

                                 View v2;
                                 v2 = ((LinearLayout) linearLayout).getChildAt(i+1);
                                 String quantity="";
                                 if (v1 instanceof TextView)
                                 { 

                                     int id=v1.getId();
                                     Log.i("tag","ids are"+id);
                                    text=((TextView) v1).getText().toString();
                                    Log.i("tag", "in tv if"+text);
                                    if(v2 instanceof EditText){
                                        Log.i("tag", "in et if");
                                        quant=((EditText) v2).getText().toString();
                                         Log.i("tag", "quant is"+quant);
                                         Log.i("tag", "text right now"+text);
                                         quantity= quant+":";
                                    }

                                    text=text+quantity;
                                    Log.i("tag", "values are "+text);

                                    orderList.add(text);
                                 }
                            }

                            oneChecked=false;

                        }
                    }



            }
            Log.i("tag", "final order List is ");
            for(String loop:orderList)
            {
                Log.i("tag", loop);
            }

            String def=orderList.toString();
            String sInst="";
            Log.i("tag", "List is "+def);
            SendOrderAsyncTask runner1 = new SendOrderAsyncTask();

            String inst=specialInstruction.getText().toString();
            Log.i("tag", "inst is "+inst);

            String TableNo =  tableNo.getText().toString();

            if(inst.equals("")){
                Log.i("tag", "inst is null ");
                asyncTaskorder=runner1.execute(def,wname,sInst,TableNo);
            }
            else if(!(inst.equals("")))
            {
                Log.i("tag", "inst does not contain null");
                sInst = specialInstruction.getText().toString();
                Log.i("tag", "in else "+sInst);
                asyncTaskorder=runner1.execute(def,wname,sInst,TableNo);
            }
        Log.i("tag", "spe inst is "+sInst);


           // orderList = null;
            Intent i = new Intent(order.this, order.class);
            startActivity(i);
            finish();
            String asyncResultText = null;
            try {
                asyncResultText = asyncTaskorder.get();
                Log.i("tag", "List in try is "+def);

            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            response = asyncResultText.trim();
            Log.i("tag", "response is "+response); 
            if(response.equals("inservertrue"))
            {
                Log.i("tag", "order sent");
            }


        }
    });



}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.login, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

我不知道你的任务是什么,以及为什么你需要返回自定义纯文本。不过我建议你使用ControllerActionInvoker。启用意图后,它将生成非常易读的json。此外,它可以很容易地将其重用于任何类型的任何复杂性。

此外,如果您需要返回数据,没有任何GUI等,请查看Newtonsoft-based JsonNetResult from this answer