There is a Grid with data which is loaded in View on selecting Edit button of a record in a row i was suppose to load a Bootstrap - Modal with selected data . Is this possible to achieve I tried of many tutorial but no use Help me in doing it. I Am new to Bootstrap and jQuery.

Grid Image

On clicking Edit button it has to displayed in a Model for performing operation.

I have a Web Service application written in C#. I want it to handle a basic request, namely, from a form, it should get file name and file content and save it to Web Service's working directory. The code is:

[WebMethod]
    public void PutFile(byte[] buffer, string filename)
    {
        BinaryWriter binWriter = new BinaryWriter(File.Open(Server.MapPath(filename), FileMode.CreateNew, FileAccess.ReadWrite));
        binWriter.Write(buffer);
        binWriter.Close();
    }

When I invoke it by running xsp in the directory of .asmx file, I can use other Web Services, such as add two numbers, etc. However when I invoke PutFile method, I get following error

500 - Internal Server Error System.ArgumentException: WebChangeTypeFailed Parameter name: type ---> System.FormatException: Input string was not in a correct format.

And follows some function errors.

I am new for developing Web Service applications using .NET and I am not sure about the cause of this problem. I've looked at web.config file and I didn't notice something strange. web.config file is:

    <?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation defaultLanguage="C#" debug="true">
      <assemblies>
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
        <add assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      </assemblies>
    </compilation>
    <customErrors mode="RemoteOnly">
    </customErrors>
    <authentication mode="None">
    </authentication>
    <authorization>
      <allow users="*" />
    </authorization>
    <httpHandlers>
    </httpHandlers>
    <trace enabled="false" localOnly="true" pageOutput="false" requestLimit="10" traceMode="SortByTime" />
    <sessionState mode="InProc" cookieless="false" timeout="20" />
    <globalization requestEncoding="utf-8" responseEncoding="utf-8" />
    <pages>
    </pages>
  </system.web>
</configuration>

Can anyone help ? Thanks.

Please how do I retrieve Data in a gridview in from form MySQL in an asp.net project data source.

Note:I used navicat lite GUI. Thanks.

I have a model named Order which has a property named Customer. The Customer is a complex object with id, name, balance, etc.

When passing the Order object to a view, the view can access the Customer object and its data as expected. However, when I post back to the Controller, the Order object is populated as expected, but the Customer object is null.

It would be nice if I could add a hidden field in the view for the Customer so it would be included in the post back, but I understand this works for single values not for complex types.

I suppose I could add all the Customer fields to the Order object, but before I do that, is there a way to include the complex object in the postback, or is there a better approach than consolidating the two objects into one by putting the individual Customer fields into the Order type?

This question already has an answer here:

I am using ExecuteScalar(). So It will return single column.

If the record is exist, It's not showing any error. If record is not found. It throws System.NullReferenceException on the following line

cmd.CommandText = "select top 1 UserID from [HQWebMatajer].[dbo].[SecurityUserDetails] where [UserID]=@UserID and [ReportName]='TotalSales';";
cmd.Parameters.AddWithValue("@UserID", ddlSecurityUser.SelectedValue);

con.Open();
string dataExist = null;
dataExist= cmd.ExecuteScalar().ToString(); // Error

I have developed a Web application using visual studio 2015,this ASP.NET MVC 4.5 application is published using FTP In Visual studio to a Machine running IIS server version 7, I don not have administrative rights to the machine hosting iis7 so i cant upgrade the iis or .net framework but can access the remote folder and path though FTP Client, error message I get on machine hosting iis when I edit the web.config I get the following errors on the machine hosting iis error 2 and further [error3][3]

I want to add a family which has many members and can have many houses. I am trying to make a form and submit the object family with collection of other objects. I have tried few things but I can only get one object to pass to controller and not the collection. What can i do?
should i make member and house partial views and render them in the view ??
Is there any way of doing this with collecting everything in JavaScript and then passing a whole family object to the controller?
I am using MVC 5 with Entity Framework. I am not able to solve this problem. Any help is appreciated.

here is an example of objects

public class family
{

    public int id { get; set; }
    public int familyname { get; set; }
    public List<member> members { get; set; }
    public List<house> houses { get; set; }
}

public class member
{
    public int id { get; set; }
    public string name { get; set; }
    public DateTime birthdate { get; set; }

    //foreign key
    public family Family { get; set; }
    public int FamilyID { get; set; }
}

public class house
{

    public int id { get; set; }
    public int number { get; set; }
    public string address { get; set; }
    //foreign key
    public family Family { get; set; }
    public int FamilyID { get; set; }
}

public class FamilyViewModel
{
   public family Family { get; set; }
    public member Member { get; set; }
    public house House { get; set;}
    public List<member> Members { get; set; } //??
    public List<house> Houses { get; set; } //??
}

View

@model WebApp.ViewModels.FamilyViewModel


@{
    ViewBag.Title = "New";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<h2>Family</h2>

@using (Html.BeginForm("Submit", "Family"))

{

<div class="form-group">
    @Html.LabelFor(m => m.Family.familyname)
    @Html.TextBoxFor(m => m.Family.familyname, new { @class = "form-control" })
</div>
<div id="member">
</div>
<div id="house">

</div>

Controller

    [HttpPost]
    public ActionResult Submit(FamilyViewModel CompleteFamily)
    {

        //What to do here?

        return View();
    }

I am trying to display a report viewer on an asp.net page. For some reason, this is what I get:

picture link

As you can see, the toolbars are not displaying properly.

I remember long time ago, writing a similar code in Visual Studio 2010, and had no problem. But now that I have this one on Visual Studio 2012, it just refuses to show properly.

I feel that this should have a quick solution but I am just not seeing it.

Any help would be appreciated.

Thanks

im trying to load the following Database structur

User -> UserTeamRelation -> Team -> Game

In this relation "Team" is already null when trying to access "user.Teams.Team".

I have the following Database structure

public class User : IdentityUser
{
    public User()
    {
        this.Id = Guid.NewGuid().ToString();
    }

    public virtual ICollection<TeamMember> Teams { get; set; }
}

public class Team
{
    public Team()
    {
        this.Id = Guid.NewGuid().ToString();
    }

    [Key]
    public string Id { get; set; }

    public virtual ICollection<TeamMember> Memberinos { get; set; }

    [Required]
    public virtual Game Game { get; set; }
}

public class TeamMember
{
    public TeamMember()
    {
        this.Id = Guid.NewGuid().ToString();
    }

    [Key]
    public string Id { get; set; }

    public virtual Team Team { get; set; }

    public virtual User Member { get; set; }
}

public class Game
{
    public Game()
    {
        this.Id = Guid.NewGuid().ToString();
    }

    [Key]
    public string Id { get; set; }

    public string Name { get; set; }
}

I tried the following code

using (var db = new ApplicationDbContext())
{
    var user = db.Users.FirstOrDefault(x => x.UserName.ToLower().Equals(username));
    if (user == null)
    {
        return new ResponseViewModel(false, "User nicht gefunden", null);
    }

    var teams = new List<Team>();
    foreach (var team in user.Teams)
    {
        teams.Add(new Team()
        {
            Description = team.Description,
            TeamName = team.Team.TeamName,
            GameName = team.Team.Game.Name
        });
    }
}

it reaches the foreach loop and finds the "Description" property. but when i try to access the team model, its null.

Any suggestion?

Kindly Help What should i do. My Theme is changed when page redirects Here is ASP.NET Code

<form id="form1" runat="server">
    <div id="dvLeft"></div>
    <div id="dvRight"></div>
    <div id="dvMiddle"></div>
    <div id="dvBottom">
        <asp:DropDownList ID="ddlTheme" runat="server" AutoPostBack="True">
            <asp:ListItem >FirstTheme</asp:ListItem>
            <asp:ListItem>SecondTheme</asp:ListItem>
            <asp:ListItem>ThirdTheme</asp:ListItem>
        </asp:DropDownList>
    </div>
</form>

And Here is C# Code:

protected override void OnPreInit(EventArgs e)
{
    if (Request["ddlTheme"] != null)
    {
        string theme = Request["ddlTheme"].ToString();
        Page.Theme = theme;
    }
    base.OnPreInit(e);
}

I have this table which contains of 3 renderOrderPropertyBlock.

<table align="center" class="wrapper header float-center">
    <tr>
        <td class="wrapper-inner background-color__yellow">
            <h5>Reservation</h5>
                @renderOrderPropertyBlock("", Model.Order.FirstName.ToString(), Model.Order2.FirstName.ToString());
                @renderOrderPropertyBlock("", Model.Order.LastName.ToString(), Model.Order2.LastName.ToString());
                @renderOrderPropertyBlock("", Model.Order.City.ToString(), Model.Order2.City.ToString());
        </td>
    </tr>
</table>

Each renderOrderPropertyBlockis calling a longer table that generates 3 columns, which is looking like this:

Example

But I need to have the text in 1 column like this:

Example

How can I print the renderOrderPropertyBlock right after eachother, instead of calling the long table after each renderOrderPropertyBlock?

ASP .NET Dynamically generate classes & compiles an assembly to the Temporary ASP.NET files.

I would like to be able to get information when this process happens. Ultimately, I would like to have an event that will fire the name of the source file and the generated class name + assembly so I could map between methods in the original source file and methods in the generated classes.

I'll appreciate your help.

I'm using a model that contains a List as a property. I'm populating this list with items I grab from SQL Server. I want the List to be hidden in the view and passed to the POST action. Later on I may want to add more items to this List with jQuery which makes an array unsuitable for expansion later on. Normally you would use

@Html.HiddenFor(model => model.MyList)

to accomplish this functionality, but for some reason the List in POST is always null.

Very simple question, anyone know why MVC behaves like this?

I am trying to route a request

/api/someName.xml?param1=123

I tried routing all requests to my default controller - MyController and it will route a call like:

http://localhost:54865/api/someName?param1=312.1232&param2=13.321

but I need not route a request like

http://localhost:54865/api/someName.xml?param1=312.1232&param2=13.321

I am not able to do that right now with the following Route map entry:

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{*uri}",
                defaults: new { controller = "MyController"});

how can I allow endpoints with extension (someName.xml) to be routed?

Thanks

This works

@Html.Action("LiveBlogHeader", "Blog", new { liveMatchItemId = "12" })

I want to set hidden field's value in it. Something like this

@Html.Action("LiveBlogHeader", "Blog", new { liveMatchItemId =  @:document.getElementById('liveMatchItemId').value })

which apparently not working. Can you please help?

I have 2 models, Subjects and Grades

i want to create a dynamic view, with for each element in Subject, create a row in a table with subject name and 3 inputs for grades, and then fill the grades and passing to the controler for operations and storage on database.

i have this model

namespace CalculaNotas.Models
public class Materias
{

public int materiasId { get; set; }

[Required]
[MinLength(length: 5, ErrorMessage = "El nombre debe contener al menos 5 caracteres")]
[MaxLength(length: 20, ErrorMessage = "El nombre debe contener maximo 2 caracteres")]
[Index(IsUnique = true)]
public string nombre { get; set; }

public virtual List<Calificaciones> calificaciones { get; set; }

}

and this

public class Calificaciones
{

const double MIN_VALUE = 0.0;
const double MAX_VALUE = 5.0;

public int Id { get; set; }

[Required]
public int materiasId { get; set; }
public virtual Materias materia { get; set; }

[Required]
[Display(Name = "Nota 1")]
[Range(minimum: MIN_VALUE, maximum: MAX_VALUE, ErrorMessage = "Debe ingresar un numero entre 0.0  y 5.0")]
public Double nota1 { get; set; }

[Required]
[Display(Name = "Nota 2")]
[Range(minimum: MIN_VALUE, maximum: MAX_VALUE, ErrorMessage = "Debe ingresar un numero entre 0.0  y 5.0")]
public Double nota2 { get; set; }

[Required]
[Display(Name = "Nota 3")]
[Range(minimum: MIN_VALUE, maximum: MAX_VALUE, ErrorMessage = "Debe ingresar un numero entre 0.0  y 5.0")]
public Double nota3 { get; set; }

[Display(Name = "Resultado")]
public Double resultado { get; set; }


}

the controller is

// GET: Calificaciones/Create
public ActionResult Create()
{
    var materias = db.Materias.ToList();
    ViewBag.materias = materias;
    return View();
}

// POST: Calificaciones/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for 
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,materiasId,nota1,nota2,nota3,resultado")] Calificaciones calificaciones)
{
    if (ModelState.IsValid)
    {
        db.Calificaciones.Add(calificaciones);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    ViewBag.materiasId = new SelectList(db.Materias, "materiasId", "nombre", calificaciones.materiasId);
    return View(calificaciones);
}

and the view

@model  CalculaNotas.Models.Calificaciones
@{
ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm())
{
 @Html.AntiForgeryToken()

<div class="form-horizontal">
 <h4>Calificaciones</h4>

<table class="table table-bordered">
    <tr >
        <th class="col-md-1"> @Html.DisplayNameFor(model => model.materia) </th>
        <th class="col-md-1" style="text-align:center">@Html.DisplayNameFor(model => model.nota1)</th>
        <th class="col-md-1" style="text-align:center">@Html.DisplayNameFor(model => model.nota2)</th>
        <th class="col-md-1" style="text-align:center">@Html.DisplayNameFor(model => model.nota3)</th>
    </tr>

    @foreach (var materia in (IEnumerable<CalculaNotas.Models.Materias>)ViewBag.materias)
    {
        <tr >
            <td class="col-md-1">@Html.DisplayFor(model => materia.nombre)</td>
            <td class="col-md-1">
                @Html.EditorFor(model => model.nota1, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.nota1, "", new { @class = "text-danger" })
            </td>
            <td class="col-md-1">
                @Html.EditorFor(model => model.nota2, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.nota2, "", new { @class = "text-danger" })
            </td>
            <td class="col-md-1">
                @Html.EditorFor(model => model.nota3, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.nota3, "", new { @class = "text-danger" })
            </td>

the view render:

I want to create multiple rows

i tried wit IEnumerable but it doesn't work any help?

I need to create a Trail and this trail has sub trails and the subtrails has levels, I have three DropDownList. where trails has one dropdown and same subtrails and levels.

The problem is when I attempt to create a new Trail, because the dropdown has a TrailId to show the all trails existing, depending which trail is selected, an ajax is ran for filtering the subtrails and show single sub trails depending trail selected.

This view is when creating:

View Creating This code is the view:

@model DefinityFirst.Mobile.Admin.Web.Services.Marvel.Contracts.ListTrailSubTrailLevelContract
@inject DefinityFirst.Mobile.Admin.Web.Services.Marvel.IMarvelServices DropDownDataHelper

@{
    ViewBag.Title = "Create";
}@if (!ViewData.ModelState.IsValid)
{
    <div class="alert alert-danger alert-dismissible" role="alert">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <strong>Warning!</strong> @Html.ValidationMessage("Error")
    </div>
}
<h2>Create</h2>
<p>New TrailSubTRailLEvel</p>
@using (Html.BeginForm("TrailSubTrailLevel", "TrailSubTrailLevel", FormMethod.Post, new { id = "demoForm" }))
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        <h4>Trail</h4>

        <div class="form-group" id="divOne">
            @Html.Label("", "Trail", new { @class = "control-label col-md-2" })
            <div class="col-md-10" id="partialDiv">

                @Html.DropDownListFor(model => model.TrailId, await DropDownDataHelper.GetTrailsDdl(), "Select one", new { @class = "form-control", onchange = "SelectedIndexChanged()" })

                @Html.ValidationMessageFor(model => model.TrailId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.Label("", "SubTrail", new { @class = "control-label col-md-2", @name = "Subtrail", @id = "Subtrail" })
            <div class="col-md-10">

                @Html.DropDownList("SubTrailId", new SelectList(string.Empty, "Value", "Text"), "Please select a SubTrail", new { @class = "form-control", @id = "SubtrailId", @name = "SubtrailId" })
                @Html.ValidationMessageFor(model => model.SubtrailId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.Label("", "Level", new { @class = "control-label col-md-2", @name = "Level", @id = "Level" })
            <div class="col-md-10">

                @Html.DropDownListFor(model => model.LevelId, await DropDownDataHelper.LevelsDdl(), "Select one", new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.LevelId, "", new { @class = "text-danger" })
            </div>
        </div>




        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-success" />
            </div>
        </div>

    </div>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    <script type="text/javascript">

        $('#SubtrailId').hide();
        $('#LevelId').hide();
        $("#Subtrail").hide();
        $("#Level").hide();

        $('#TrailId').on('change', function () {

            if (this.value != 0) {
                $("#Subtrail").show();
                $('#SubtrailId').show();



            } else {
                $('#SubtrailId').hide();
                $('#LevelId').hide(); 
            }
        })
        $('#SubtrailId').on('change', function () {

            if (this.value != 0) {

                $("#Level").show();
                $('#LevelId').show();


            } else {

                $('#LevelId').hide();

            }
        })

    </script>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script type="text/javascript">
        var URL = 'http://localhost:51514/api/TrailSubTrailLevel/JSonSubTrails';
        var dllDropDownSubTrail = $('#SubtrailId');
        var dllDropDownTrail = $('#TrailId').val();

        $(document).ready(function () {
            $('#TrailId').change(function () {
                $('#SubtrailId').html("");
                var val = $(this).val();
                $.ajax({
                    type: 'GET',
                    url: URL,
                    contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                    success: function (data) {
                        var myData = data.Value;
                        localStorage.setItem('myList', myData);

                        $.each(myData, function (key, value) {
                            if (value.TrailId == $('#TrailId').val()) {
                                console.log(value.Name)
                                $('#SubtrailId').append('<option value="' + value.Id + '">' + value.Name + '</option>');
                            }
                        });
                    },

                    error: function (data) {
                        console.log('ERROR', data.Value);
                    }
                });

            });
        });
    </script>



}

this code is where received action of click in button create, send information all DropDownList:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(ListTrailSubTrailLevelContract ListTrailSubTrailLevelContract)
{


    if (ModelState.IsValid)
    {
        await _marvelServices.CreateTrailSubTrailLevel(ListTrailSubTrailLevelContract);

        return RedirectToAction("Index", "TrailSubTrailLevel");
    }


    return View(ListTrailSubTrailLevelContract);
}

And this code is where that properties sending, but I need alone this propertie "TrailSubTrailId", because in my table alone exists two properties "LevelId" and "TrailSubtrailId", but I sending three properties and this is start the problem:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DefinityFirst.Mobile.Admin.Web.Services.Marvel.Contracts
{
    public class ListTrailSubTrailLevelContract
    {

        public int id { get; set; }

        public int TrailId { get; set; }

        public string TrailName { get; set; }

        public int SubtrailId { get; set; }

        public string SubTrailName { get; set; }

        public int LevelId { get; set; }

        public string LevelName { get; set; }

        public int TrailSubtrailId { get; set;  }

    }
}

THIS PART IS WHERE CONSUMING SERVICE

This code is TrailSubTrailContract:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DefinityFirst.CarrerPath.Model.Contracts
{
    public class TrailSubTrailLevelContract
    {
        public TrailSubTrailLevelContract()
        {
            //Level = new HashSet<LevelContract>();
            //TrailSubtrail = new HashSet<TrailsSubTrailsListContract>();
        }

        public int Id { get; set; }

        public int TrailSubtrailId { get; set; }

        public int LevelId { get; set; }

        public TrailsSubTrailsListContract TrailSubtrail { get; set; }

        public LevelContract Level { get; set; }
    }
}

I'm trying to add data to a MySQL Server database.

Here is the code:

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim connection As SqlConnection = New SqlConnection("Data Source=192.168.3.173\hidp;Initial Catalog=HIDP;Persist Security Info=True;User ID=intranet;Password=kikapu;APP=Intranet")
    Dim sql As String = "Insert into [RAVARIAS].[StockMovimentos] ([CodHospital], [utilizador], [servico], [CodDevice], [CodConsumivel], [TipoMovimento], [DtMovimento], [Qtd]) values (@CodHospital, @utilizador, @servico, @CodDevice, @CodConsumivel, @TipoMovimento, @DtMovimento, @Qtd)"
    Dim cmd As SqlCommand = New SqlCommand(sql, connection)
    cmd.Parameters.AddWithValue("@CodHospital", Session("Codhospital"))
    cmd.Parameters.AddWithValue("@utilizador", TextBox1.Text)
    cmd.Parameters.AddWithValue("@servico", TextBox2.Text)
    cmd.Parameters.AddWithValue("@CodDevice", DropDownList3.SelectedItem)
    cmd.Parameters.AddWithValue("@CodConsumivel", DropDownList4.SelectedItem)
    cmd.Parameters.AddWithValue("@TipoMovimento", DropDownList2.SelectedItem)
    cmd.Parameters.AddWithValue("@DtMovimento", Calendar1.SelectedDate)
    cmd.Parameters.AddWithValue("@Qtd", TextBox4.Text)
    connection.Open()
    cmd.ExecuteNonQuery()
    connection.Close()
    TextBox1.Text = ""
    TextBox2.Text = ""
    TextBox4.Text = ""
    DropDownList2.ClearSelection()
    DropDownList3.ClearSelection()
    DropDownList4.ClearSelection()
    Calendar1.SelectedDates.Clear()
End Sub

When I click on the button nothing happens.

I am developing a webapp in ASP.NET framework 3.5.2.

After draging the Chart Control from the toolbox to where I want it in my .aspx page, there seems to be this added at the top of the document:

<%@ Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>

When I run I get the error: "Error executing child request for ChartImg.axd."

I have tried adding the following into system.web in my Web.config

<httpHandlers>
    <add path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false" />
</httpHandlers>

Then I get:

HTTP Error 500.23 - Internal Server Error

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.

Most likely causes: •This application defines configuration in the system.web/httpHandlers section.

It says that I can try to "Migrate the configuration to the system.webServer/handlers section".

How do I do this and how till it affect my webapp? Will something else stop working and is it possible to revert the migration?

I am trying to understand how to work with fact that web is stateless and I am not doing well so far. I would appreciate if you could help me with some questions on below code.

  1. Is there a way how display a specific title (based on its id) for a product? It has List as a property and things I have found so far was not clear to me or does not bring the answer. //Would it be better if "nested object property" would not be in a list?

  2. When I do Databind() on dropLanguage is the abbreviation property lost or can be somehow accessed thru viewstate? Something like var getMyCollectionBack = dropLanguage.DataSource; Label1.Text = getMyCollectionBack.First().Abbreviation would be awesome.

  3. Well working with already obtained data without a need to call back to server is completely new to me. I read some basic tutorials on AJAX but this thing can get complicated pretty quickly. Check the code below for the actual question.

  4. Is this a way how to store things that are not assigned to any control? We have been taught "keep database calls and amount of pulled data as low as you can". With web application "make a page as small as possible and call db everytime you need" is a different approach. I guess both of them are correct and it is always about given scenario.

  5. Does ViewState work on mobile devices? I have read somewhere it does not which kinda scares me.

Data to work with

public class BLL
{

    public List<LanguageDto> GetLanguages()
    {
        var list = new List<LanguageDto>();

        list.Add(new LanguageDto() {Id = 100, Abbreviation = "EN", Title = "English"});
        list.Add(new LanguageDto() { Id = 101, Abbreviation = "DE", Title = "German" });
        list.Add(new LanguageDto() { Id = 102, Abbreviation = "SK", Title = "Slovak" });
        list.Add(new LanguageDto() { Id = 103, Abbreviation = "PL", Title = "Polish" });

        return list;
    }

    public List<ItemTitleDto> GetTitles(int item = 0)
    {
        var list = new List<ItemTitleDto>();

        if (item == 1)
        {
            list.Add(new ItemTitleDto() { ItemId = 1, Language = new LanguageDto() { Id = 101, Abbreviation = "DE" }, Title = "ITEM -- 1 --", Description = "Eine ball (Thanks google!)" });
            list.Add(new ItemTitleDto() { ItemId = 1, Language = new LanguageDto() { Id = 100, Abbreviation = "EN" }, Title = "ITEM -- 1 --", Description = "Description of item 1" });
            list.Add(new ItemTitleDto() { ItemId = 1, Language = new LanguageDto() { Id = 103, Abbreviation = "PL" }, Title = "ITEM -- 1 --", Description = "Powodzenia (Thanks google!)" });
            return list;
        }
        if (item == 2)
        {
            list.Add(new ItemTitleDto() { ItemId = 2, Language = new LanguageDto() { Id = 102, Abbreviation = "SK" }, Title = "ITEM -- 2 --", Description = "Obed" });
            list.Add(new ItemTitleDto() { ItemId = 2, Language = new LanguageDto() { Id = 103, Abbreviation = "PL" }, Title = "ITEM -- 2 --", Description = "Obiad (Thanks google!)" });
            list.Add(new ItemTitleDto() { ItemId = 2, Language = new LanguageDto() { Id = 100, Abbreviation = "EN" }, Title = "ITEM -- 2 --", Description = "Lunch" });
            list.Add(new ItemTitleDto() { ItemId = 2, Language = new LanguageDto() { Id = 101, Abbreviation = "DE" }, Title = "ITEM -- 2 --", Description = "Mittagessen (Thanks google!)" });
            return list;
        }
        if (item == 3)
        {
            list.Add(new ItemTitleDto() { ItemId = 3, Language = new LanguageDto() { Id = 103, Abbreviation = "EN" }, Title = "ITEM -- 3 --", Description = "Something pink" });
            return list;
        }

        list.Add(new ItemTitleDto() { ItemId = 0, Language = new LanguageDto() { Id = 100, Abbreviation = "EN" }, Title = "Some item -- 0 --", Description = "Description of item 1" });
        list.Add(new ItemTitleDto() { ItemId = 0, Language = new LanguageDto() { Id = 101, Abbreviation = "DE" }, Title = "ITEM -- 0 --", Description = "Some of us are not bilingual :(" });
        return list;

    }

    public List<ItemDto> GetItems()
    {
        var list = new List<ItemDto>();
        list.Add(new ItemDto() {Id = 1, Color = "Yellow", Weight = 1.25m});
        list.Add(new ItemDto() { Id = 2, Color = "Green", Weight = 571.1m });
        list.Add(new ItemDto() { Id = 3, Color = "Pink", Weight = 0.5m });

        return list;
    }
}

[Serializable]
public class ItemDto
{
    public int Id { get; set; }
    public decimal Weight { get; set; }
    public string Color { get; set; }

    public List<ItemTitleDto> Titles { get; set; }
}

[Serializable]
public class ItemTitleDto
{
    public int ItemId { get; set; }
    public LanguageDto Language { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
}
[Serializable]
public class LanguageDto
{
    public int Id { get; set; }
    public string Abbreviation { get; set; }
    public string Title { get; set; }
}

HTML

    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="grdItem" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField Visible="True" DataField="Id" />
                <asp:BoundField Visible="True" DataField="Color" />
                <asp:BoundField Visible="True" DataField="Titles" />
            </Columns>
        </asp:GridView>
        <br />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        <br />
        <br />
        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
        <br />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
        <br />
        <asp:DropDownList ID="dropLanguage" runat="server" OnSelectedIndexChanged="dropLanguage_SelectedIndexChanged">

        </asp:DropDownList>
    </div>
</form>

Code behind

public partial class WebForm1 : System.Web.UI.Page
{
    private BLL _domain;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (_domain == null)
        {
            _domain = new BLL();
        }

        if(!Page.IsPostBack)
        {
            var result = _domain.GetItems();


            foreach (var item in result)
            {
                item.Titles = _domain.GetTitles(item.Id);
            }
            grdItem.DataSource = result;
            grdItem.DataBind();

            dropLanguage.DataSource = _domain.GetLanguages();
            dropLanguage.DataTextField = "Title";
            dropLanguage.DataValueField = "Id";

            dropLanguage.DataBind();


            //       4
            ViewState["MyUniqueString"] = result;

        }

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Label2.Text = dropLanguage.SelectedValue.ToString();

    }

    protected void dropLanguage_SelectedIndexChanged(object sender, EventArgs e)
    {
        Label1.Text = String.Empty;

        //      2   ****************************************************
        /* I Would like to set Label1.Text to LangugageDto.Abbreviation.
         * Was it saved somewhere or its lost since it was't "hardwired" somehow before dropLanguage.Databind*/

        //      3
        /* It would be nice to Label1.Text and Label2.Text without a need of postback. 
         * I assume some AJAX or just a javascript is needed right? Could you please show me how to set Label2.Text
         * on SelectedIndexChanged event? */

    }
}

I have files stored in a database that I need a Web API to return. The database call correctly returns the proper byte array (Breakpoint shows the array being around 67000 in length, which is correct), but when I make a call to the Web API, I never get that content in the response. I've tried using a MemoryStream and ByteArrayContent, and neither give me the results I should be getting. I've tried calling from both Postman and my MVC application, but neither return the byte array, just the basic response information with headers/success/etc.

public HttpResponseMessage GetFile(int id)
{
    var fileToDownload = getFileFromDatabase(id);
    if (fileToDownload == null)
    {
        return new HttpResponseMessage(HttpStatusCode.BadRequest);
    }
    var response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new ByteArrayContent(fileToDownload.FileData); //FileData is just a byte[] property in this class
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    return response;
}

Typical Response I get (with no byte content anywhere to be found):

{
  "version": {
    "major": 1,
    "minor": 1,
    "build": -1,
    "revision": -1,
    "majorRevision": -1,
    "minorRevision": -1
  },
  "content": {
    "headers": [
      {
        "key": "Content-Disposition",
        "value": [
          "attachment"
        ]
      },
      {
        "key": "Content-Type",
        "value": [
          "application/octet-stream"
        ]
      }
    ]
  },
  "statusCode": 200,
  "reasonPhrase": "OK",
  "headers": [],
  "requestMessage": null,
  "isSuccessStatusCode": true
}

Maybe I'm misinterpreting how I should be handling this data, but I feel like this should be getting returned from the Web API call since I explicitly add it.