none
MyData is a varaible but is used as a type RRS feed

  • Question

  •  @{    result = Model.ModuleName.Image;           

             var results = JsonConvert.DeserializeObject<List<MyData>>(result);        

                List<string> imageSrc = new List<string>();       

                 foreach (var item in results)                    {    

                        imageSrc.Add("~/Content/UploadedImages/" + item.Filename );                   

    }                    } }

    At the top of the cshtml file i have:

    @{
        List<string> MyData;
        string result  ;
    }

    How to declare as a type?

    Monday, November 4, 2019 2:46 PM

All replies

  • Try the following for declaring variables.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Monday, November 4, 2019 2:50 PM
    Moderator
  • You are getting this error because you declare `MyData` as a variable of type `List<string>`. Then later you are trying to get a List<MyData> from JSON. List<T> requires a type (e.g. List<string>, List<Product>, etc). What C# data type does the JSON contained in your `Model.ModuleName.Image` property represent? Whatever that type is would be what you would use in List<T> in lieu of `MyData`. Also note that the code you posted at the top of your file probably isn't needed at all so remove it.

    Finally note that you should post MVC questions in the ASP.NET forums. However they are going to immediately tell you that you are doing your model wrong. Views never do this kind of work. You might as well just put all your code in the view. The model should contain all the data the view needs already converted to the appropriate format. The only purpose of a view is to format and render the provided data. Therefore all this code should just go away anyway. Your model should have a property that exposes the list of whatever you're trying to JSON convert from. Then your view is a simple foreach.

    public class MyImage
    {
       public string Filename { get; set; }
    }
    
    public class MyModel
    {
       public IEnumerable<MyImage> Images { get; set; } 
    }
    
    //View
    @foreach (var image in Model.Images) {
       <img src="@image">...
    }
    
    //Code to create the model
    var model = new MyModel() { … };
    
    //Convert here (or do it in a helper method, doesn't matter)
    model.Images = JsonConvert.DeserializeObject<List<MyImage>>(jsonStringFromYourSourceThatYouWereSettingToModuleNameImage);


    Michael Taylor http://www.michaeltaylorp3.net

    Monday, November 4, 2019 3:10 PM
    Moderator