I'm building a webapp in ASP.NET and am trying to get a button (a Panel) to load a "window" or sub application to add new users. I want the div holding the buttons to transitionally clear or be "deleted" and in the same window, load the corresponding application/div. Most people suggest Ajax but none of the answers I've found have the desired effect I want. Below is a sample of the button/panel item which is contained in a div that is 100% vh and 100% vw. I'm not exactly familiar with jQuery either which doesn't help.

Thanks in advance.

<div class="admin-panel">
            <div class="row admin-controls">
                <div class="col-md-2"></div>
                <div class="col-md-2">
                    <asp:Panel runat="server" >
                        <div class="admin-control-item" onclick=""><!-- This is the button to load the application -->
                             <i class="material-icons md-48">people</i>
                             <h3>Current Users</h3>
                         </div>
                    </asp:Panel>
                </div>
...
</div>

I have a MVC Web API (hosted in IIS) which is in the wwwroot folder and locally accessible within the network.I can execute api calls like this: http://mylocalapi:133/api/Values/Get and I get a result.

I have an external site which is http://example.org and I would like to execute the same http://mylocalapi:133/api/Values/Get.

I have CORS set up in my API like this:

[EnableCors(origins: "http://example.org", headers: "*", methods: "*")]

But I keep getting the following error:

XMLHttpRequest cannot load http://mylocalapi:133. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.org' is therefore not allowed access.

So get around it, I created a virtual directory (APICALLS) in my external site and created a web.config file which will point to the local IIS site:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <httpRedirect enabled="true" destination="http://mylocalapi:133" exactDestination="true" />
    </system.webServer>
</configuration>

When I do that, I try to access the API like this: http://example.org/APICALLS/api/Values/Get but I get the following error:

XMLHttpRequest cannot load http://mylocalapi:133. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.org' is therefore not allowed access.

What am I doing wrong and how can I resolve the issue.

I've a Many to Many relation between a student (etudiant) and a course (cours) table which is called studentCours in SQL but not use as a model in Entity Framework (i've taken the habit of it now, even if i think its weird).

I need to show the result of the student (which is on another table etuResult) but the student may not have any result (nullable int) yet as the year is still in progress !

I'm able to get the value of studentCours and show them and also of studentResult, but i'm not able to show the concatenation of both (and leave the result empty or with other value than a number between 1 and 20).

On the following picture you can see :

On the left : the student with the id 3 has 2 cours with the id 1 and 10 (i dont know why the course_id 1 appears twice...) => These are the course he's following.

On the right : The student with the id 3 has one result for the course_id 10 and has the result 10/20

getResult (left) and getCourse (right)

Here are my two queries to get the data :

var etuCours = from c in bdd.cours
         where c.etudiant.Any(e => e.etudiant_id == id)
         select new resultCours { cours_id = c.cours_id, libelle = c.libelle, code = c.code, annee = c.annee };
IEnumerable<resultCours> etuResult = from er in bdd.etuResult
         where er.etudiant_id == id
         select new resultCours { cours_id = er.cours_id, cote = er.cote };

I want to execute a RegisterStartupScript calling a Javascript function after certain processes happen in my code behind. It is basically a Loading loop decoration made in CSS3. I show it (with javascript) on buttons clientclick, when I know the process will take a while and I hide it when the process is finished. Everything works fine, but now I have a process in Which I download a file using another empty webform using response.redirect. The file is downloaded fine, but the RegisterStartupScript call does not work. I understand the response is the problem, but nor I need to work in a workaround to solve this (I do not want to change the whole way, cause it is implemented in many other pages and processes. I wil provide the related code (not all), in case you can give me a direct way to solve it.

Javascript

function LoadingLoopOn()
{
    $('#outerAlignId').addClass("outerAlign");
    $('#middleAlignId').addClass("middleAlign");
    $('#innerAlignId').addClass("innerAlign");
    $('#OutterCircleId').addClass("OutterCircle");
    $('#InnerCircleId').addClass("InnerCircle");
    $('#Loadinglbl').addClass("LoadingLabelStyle");
}

function LoadingLoopOff()
{
    $('#outerAlignId').removeClass("outerAlign");
    $('#middleAlignId').removeClass("middleAlign");
    $('#innerAlignId').removeClass("innerAlign");
    $('#OutterCircleId').removeClass("OutterCircle");
    $('#InnerCircleId').removeClass("InnerCircle");
    $('#Loadinglbl').removeClass("LoadingLabelStyle");
}

HTML (it is on the master page, to be able to used it in every webform)

<asp:Panel ID="outerAlignId" ClientIDMode="Static" runat="server" CssClass="outerAlign">
    <div id="middleAlignId" class="middleAlign">
        <div id="innerAlignId" class="innerAlign">
            <div id="OutterCircleId" class="OutterCircle"></div>
            <div id="InnerCircleId" class="InnerCircle"></div>
            <asp:Label ID="Loadinglbl" ClientIDMode="Static" runat="server" Text="Loading..." CssClass="LoadingLabelStyle"></asp:Label>
        </div>
    </div>
</asp:Panel>

HTML Button Sample Where I want to used it

<asp:ImageButton ID="ExportExId" ClientIDMode="Static" runat="server" OnClientClick="LoadingLoopOn();"  OnClick="ExportExId_Click" CssClass="..." ImageUrl="..." />

And the CS# Code behind

    protected void ExportExId_Click(object sender, ImageClickEventArgs e)
    {
        //...
        //Many code and DB treatment goes here, to finally get a temporally Excel file in the server
        //..

        //I call the page with the file name and path
        Response.Redirect(String.Format("DownloadForm.aspx?FileName={0}&Path={1}", fileExported.Name, "Temp" + UserName));

        //This piece of code must be excuted in its webform after the redirect (once ee finished)
        ScriptManager.RegisterStartupScript(this, GetType(), "LoadingLoopOff", "LoadingLoopOff();", true);

    }

Many thanks,

I can't figure out what I'm doing wrong here. Trying to dynamically fill a dropdownlist inside a gridview and it keeps telling me the object reference is not set to an instance of an object.

First, my ASPX:

<asp:Panel runat="server" ID="ShowDiv3" Visible="false" BorderStyle="Solid" BorderWidth="0"  Width="1389px">
        <asp:Label ID="lblShowDiv3Title" runat="server" Text="Root Causes:    " Font-Bold="true"></asp:Label><asp:DropDownList ID="ddlRootCauses" runat="server" Width="300px" OnSelectedIndexChanged="ddlRootCauses_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
        <br />
        <%-- This line needed to be commented out when paging was removed: AllowPaging="True"  AllowCustomPaging="True" PageSize="10" --%>
        <div id="divGrid3" style='width:1290px; overflow:auto'>
    <asp:GridView ID="DataGrid_RootCauses" runat="server" 
        AllowSorting="True" OnSorting="DataGrid_RootCauses_Sorting" AutoGenerateColumns="False" ShowFooter ="true" CellPadding="1" 
        CssClass="hoverTable"
        HeaderStyle-BackColor="#4DA6A6" HeaderStyle-BorderColor="#4DA6A6" 
        HeaderStyle-Font-Size="Small" HeaderStyle-ForeColor="White"
        FooterStyle-BackColor="#4DA6A6" FooterStyle-BorderColor="#4DA6A6" FooterStyle-ForeColor="White"
        DataKeyNames="root_cause_id"
                        OnRowDataBound="DataGrid_RootCauses_RowDataBound"
        OnRowCancelingEdit="DataGrid_RootCauses_CancelCommand"   
        OnRowEditing="DataGrid_RootCauses_EditCommand" 
        OnRowDeleting="DataGrid_RootCauses_DeleteCommand"
        OnRowUpdating="DataGrid_RootCauses_UpdateCommand">  
            <Columns>  

            <asp:TemplateField HeaderText="LPI Due">  
            <ItemStyle HorizontalAlign="Center"></ItemStyle>
            <ItemTemplate>  
                <asp:Label ID="lbl_LPI_DUE" runat="server" Width="70px" Text='<%#Eval("LPI_DUE") %>'></asp:Label>  
            </ItemTemplate>  
            <EditItemTemplate>  
                <asp:DropDownList ID="ddl_RC_LPI_DUE" runat="server" Width="70px" Text='<%#Eval("LPI_DUE") %>'>
                    <asp:ListItem Value=""> - </asp:ListItem>
                    <asp:ListItem Value="N"> N </asp:ListItem>
                    <asp:ListItem Value="Y"> Y </asp:ListItem>
                </asp:DropDownList>  
            </EditItemTemplate>  
            <FooterTemplate>  
                <asp:DropDownList ID="nddl_RC_LPI_DUE" runat="server" Width="70px" >
                    <asp:ListItem Value=""> - </asp:ListItem>
                    <asp:ListItem Value="N"> N </asp:ListItem>
                    <asp:ListItem Value="Y"> Y </asp:ListItem>
                </asp:DropDownList>  
            </FooterTemplate>
        </asp:TemplateField>                    

        <asp:TemplateField HeaderText="Root Cause Category">  
            <ItemTemplate>  
                <asp:Label ID="lbl_LPI_Category" runat="server" Width="170px" Text='<%#Eval("LPI_Category") %>'></asp:Label>  
            </ItemTemplate>  
            <EditItemTemplate>  
                <asp:DropDownList ID="ddl_RC_LPI_Category" runat="server" Width="170px" Text='<%#Eval("LPI_Category") %>'></asp:DropDownList>
            </EditItemTemplate>  
            <FooterTemplate>  
                <asp:DropDownList ID="nddl_RC_LPI_Category" runat="server" Width="170px" ></asp:DropDownList>
            </FooterTemplate>
        </asp:TemplateField>                   

        <asp:TemplateField HeaderText="Root Cause Reason">  
            <ItemTemplate>  
                <asp:Label ID="lbl_LPI_Reason" runat="server" Width="370px" Text='<%#Eval("LPI_reason") %>'></asp:Label>  
            </ItemTemplate>  
            <EditItemTemplate>  
                <asp:TextBox ID="txt_RC_LPI_Reason" runat="server" Width="370px" Text='<%#Eval("LPI_reason") %>'></asp:TextBox>  
            </EditItemTemplate>  
            <FooterTemplate>  
                <asp:TextBox ID="ntxt_RC_LPI_Reason" runat="server" Width="370px" ></asp:TextBox>  
            </FooterTemplate>
        </asp:TemplateField>                 

        <asp:TemplateField HeaderText="Business Owned">  
            <ItemStyle HorizontalAlign="Center"></ItemStyle>
            <ItemTemplate>  
                <asp:Label ID="lbl_Business" runat="server" Width="70px" Text='<%#Eval("Business") %>'></asp:Label>  
            </ItemTemplate>  
            <EditItemTemplate>  
                <asp:DropDownList ID="ddl_RC_Business" runat="server" Width="70px" Text='<%#Eval("Business") %>'>
                    <asp:ListItem Value=""> - </asp:ListItem>
                    <asp:ListItem Value="N"> N </asp:ListItem>
                    <asp:ListItem Value="Y"> Y </asp:ListItem>
                </asp:DropDownList>  
            </EditItemTemplate>  
            <FooterTemplate>  
                <asp:DropDownList ID="nddl_RC_Business" runat="server" Width="70px" >
                    <asp:ListItem Value=""> - </asp:ListItem>
                    <asp:ListItem Value="N"> N </asp:ListItem>
                    <asp:ListItem Value="Y"> Y </asp:ListItem>
                </asp:DropDownList>  
            </FooterTemplate>
        </asp:TemplateField>   

        <asp:TemplateField HeaderText="CP Owned">  
        <ItemStyle HorizontalAlign="Center"></ItemStyle>
            <ItemTemplate>  
                <asp:Label ID="lbl_CP" runat="server" Width="70px" Text='<%#Eval("CP") %>'></asp:Label>  
            </ItemTemplate>  
            <EditItemTemplate>  
                <asp:DropDownList ID="ddl_RC_CP" runat="server" Width="70px" Text='<%#Eval("CP") %>'>
                    <asp:ListItem Value=""> - </asp:ListItem>
                    <asp:ListItem Value="N"> N </asp:ListItem>
                    <asp:ListItem Value="Y"> Y </asp:ListItem>
                </asp:DropDownList>  
            </EditItemTemplate>  
            <FooterTemplate>  
                <asp:DropDownList ID="nddl_RC_CP" runat="server" Width="70px" >
                    <asp:ListItem Value=""> - </asp:ListItem>
                    <asp:ListItem Value="N"> N </asp:ListItem>
                    <asp:ListItem Value="Y"> Y </asp:ListItem>
                </asp:DropDownList>  
            </FooterTemplate>
        </asp:TemplateField>                    

        <asp:TemplateField HeaderText="Non-CP Owned">  
        <ItemStyle HorizontalAlign="Center"></ItemStyle>
            <ItemTemplate>  
                <asp:Label ID="lbl_Non_CP" runat="server" Width="70px" Text='<%#Eval("Non_CP") %>'></asp:Label>  
            </ItemTemplate>  
            <EditItemTemplate>  
                <asp:DropDownList ID="ddl_RC_Non_CP" runat="server" Width="70px" Text='<%#Eval("Non_CP") %>'>
                    <asp:ListItem Value=""> - </asp:ListItem>
                    <asp:ListItem Value="N"> N </asp:ListItem>
                    <asp:ListItem Value="Y"> Y </asp:ListItem>
                </asp:DropDownList>  
            </EditItemTemplate>  
            <FooterTemplate>  
                <asp:DropDownList ID="nddl_RC_Non_CP" runat="server" Width="70px" >
                    <asp:ListItem Value=""> - </asp:ListItem>
                    <asp:ListItem Value="N"> N </asp:ListItem>
                    <asp:ListItem Value="Y"> Y </asp:ListItem>
                </asp:DropDownList>  
            </FooterTemplate>
        </asp:TemplateField> 

        <asp:TemplateField HeaderText="Proclaim">  
        <ItemStyle HorizontalAlign="Center"></ItemStyle>
            <ItemTemplate>  
                <asp:Label ID="lbl_Proclaim" runat="server" Width="70px" Text='<%#Eval("Proclaim") %>'></asp:Label>  
            </ItemTemplate>  
            <EditItemTemplate>  
                <asp:DropDownList ID="ddl_RC_Proclaim" runat="server" Width="70px" Text='<%#Eval("Proclaim") %>'>
                    <asp:ListItem Value=""> - </asp:ListItem>
                    <asp:ListItem Value="N"> N </asp:ListItem>
                    <asp:ListItem Value="Y"> Y </asp:ListItem>
                </asp:DropDownList>  
            </EditItemTemplate>  
            <FooterTemplate>  
                <asp:DropDownList ID="nddl_RC_Proclaim" runat="server" Width="70px" >
                    <asp:ListItem Value=""> - </asp:ListItem>
                    <asp:ListItem Value="N"> N </asp:ListItem>
                    <asp:ListItem Value="Y"> Y </asp:ListItem>
                </asp:DropDownList>  
            </FooterTemplate>
        </asp:TemplateField> 

        <asp:TemplateField HeaderText="PMHS">  
        <ItemStyle HorizontalAlign="Center"></ItemStyle>
            <ItemTemplate>  
                <asp:Label ID="lbl_PMHS" runat="server" Width="70px" Text='<%#Eval("PMHS") %>'></asp:Label>  
            </ItemTemplate>  
            <EditItemTemplate>  
                <asp:DropDownList ID="ddl_RC_PMHS" runat="server" Width="70px" Text='<%#Eval("PMHS") %>'>
                    <asp:ListItem Value=""> - </asp:ListItem>
                    <asp:ListItem Value="N"> N </asp:ListItem>
                    <asp:ListItem Value="Y"> Y </asp:ListItem>
                </asp:DropDownList>  
            </EditItemTemplate>  
            <FooterTemplate>  
                <asp:DropDownList ID="nddl_RC_PMHS" runat="server" Width="70px" >
                    <asp:ListItem Value=""> - </asp:ListItem>
                    <asp:ListItem Value="N"> N </asp:ListItem>
                    <asp:ListItem Value="Y"> Y </asp:ListItem>
                </asp:DropDownList>  
            </FooterTemplate>
        </asp:TemplateField> 

        <asp:TemplateField HeaderText="Facets">  
        <ItemStyle HorizontalAlign="Center"></ItemStyle>
            <ItemTemplate>  
                <asp:Label ID="lbl_Facets" runat="server" Width="70px" Text='<%#Eval("Facets") %>'></asp:Label>  
            </ItemTemplate>  
            <EditItemTemplate>  
                <asp:DropDownList ID="ddl_RC_Facets" runat="server" Width="70px" Text='<%#Eval("Facets") %>'>
                    <asp:ListItem Value=""> - </asp:ListItem>
                    <asp:ListItem Value="N"> N </asp:ListItem>
                    <asp:ListItem Value="Y"> Y </asp:ListItem>
                </asp:DropDownList>  
            </EditItemTemplate>  
            <FooterTemplate>  
                <asp:DropDownList ID="nddl_RC_Facets" runat="server" Width="70px" >
                    <asp:ListItem Value=""> - </asp:ListItem>
                    <asp:ListItem Value="N"> N </asp:ListItem>
                    <asp:ListItem Value="Y"> Y </asp:ListItem>
                </asp:DropDownList>  
            </FooterTemplate>
        </asp:TemplateField> 

        <asp:TemplateField ItemStyle-Width="90px">  
        <ItemTemplate>  
            <asp:Button ID="btn_Edit" runat="server" Text="Edit" CommandName="Edit" />  
        </ItemTemplate>  
        <EditItemTemplate>  
            <asp:Button ID="btn_Update" runat="server" Text="Update" CommandName="Update"/>  
            <asp:Button ID="btn_Cancel" runat="server" Text="Cancel" CommandName="Cancel"/>  
        </EditItemTemplate>  
        <FooterTemplate>
            <asp:Button ID="btn_Add" runat="server" Text="Add" OnClick="DataGrid_RootCauses_RowCreated" />
        </FooterTemplate>
        </asp:TemplateField>  
        <asp:TemplateField>  
        <ItemTemplate>  
            <asp:Button ID="btn_Delete" runat="server" OnClientClick="javascript:return confirm('Are you sure?');" Text="Delete" CommandName="Delete" />  
        </ItemTemplate>  
        </asp:TemplateField>        
        <asp:TemplateField HeaderText="Cause ID">  
        <ItemTemplate>  
            <asp:Label ID="lbl_Cause_ID" runat="server" Text='<%#Eval("root_cause_id") %>'></asp:Label>  
        </ItemTemplate>  
        </asp:TemplateField>        

        </Columns>  
    </asp:GridView>  
    <asp:Label ID="lblEmpty1" runat="server" Visible="false" Style="font-weight:bold; font-size:large;"></asp:Label>
    </div> 
</asp:Panel>

Now, the code-behind:

protected void  ddlRootCauses_SelectedIndexChanged(object sender, EventArgs e)
{
    LoadRootCauseGrid();

    OracleConnection conn = GetConnection();
    try
    {
        {
            // ddlRootCauses
            OracleCommand cmd6 = new OracleCommand();
            cmd6.CommandType = CommandType.StoredProcedure;
            cmd6.CommandText = "SP_LPI_MAINT_LIST_ROOTCAUSE";
            cmd6.Connection = conn;

            //cmd3.Parameters.Add("v_Lookup_Value", OracleType.VarChar, 20).Value = "LEAD";
            cmd6.Parameters.Add("vRootCauseList", OracleType.Cursor).Direction = ParameterDirection.Output;

            var SearchAdapter6 = new OracleDataAdapter(cmd6);
            var ds6 = new DataTable();
            SearchAdapter6.Fill(ds6);

            DataView view = new DataView(ds6);
            DataTable distinctValues = new DataTable();
            distinctValues = view.ToTable(true, "LPI_Category");

            // Fill all of the dropdowns from the same data adapter
            {
                //This one works fine
                ddlRootCauses.DataSource = distinctValues;
                ddlRootCauses.DataTextField = "LPI_Category";
                ddlRootCauses.DataValueField = "LPI_Category";
                ddlRootCauses.DataBind();
                ddlRootCauses.Items.Insert(0, new ListItem("All", ""));

                //This one send me down to the Catch block on the first line
                ddl_RC_LPI_Category.DataSource = distinctValues;
                ddl_RC_LPI_Category.DataTextField = "LPI_Category";
                ddl_RC_LPI_Category.DataValueField = "LPI_Category";
                ddl_RC_LPI_Category.DataBind();
                ddl_RC_LPI_Category.Items.Insert(0, new ListItem("All", ""));

                nddl_RC_LPI_Category.DataSource = distinctValues;
                nddl_RC_LPI_Category.DataTextField = "LPI_Category";
                nddl_RC_LPI_Category.DataValueField = "LPI_Category";
                nddl_RC_LPI_Category.DataBind();
                nddl_RC_LPI_Category.Items.Insert(0, new ListItem("All", ""));

            }

            ds6.Dispose();
            cmd6.Dispose();
            SearchAdapter6.Dispose();

            conn.Close();
        }
    }
    catch (Exception ex)
    {
            Response.Write(ex.Message);
            conn.Close();
    }

}

Oddly enough, ddlRootCauses gets populated with no problems. But, that dropdownlist is outside of the gridview. I don't understand why it's having trouble with the dropdownlist inside the gridview. And, it can't just be because gridviews don't like dropdowns; the Y/N ones with hardcoded listitems work fine.

I am having mvc 4.5 project project and I am trying to use angular cli but it seems like I am missing steps to make it work, I have tried to use angular 2 seed project and it works fine. please help me with angular cli configuration on MVC 4.5.

thank you.

I write id to TempData in one action method like this

[HttpPost]
    public ActionResult Index(string question1, string question2, string question3, string question4, string question5, string question6, string question7, string question8, string question9, string question10, Int32 id)
    {
        QuestionBlock question = new QuestionBlock
        {
            Question1 = question1,
            Question2 = question2,
            Question3 = question3,
            Question4 = question4,
            Question5 = question5,
            Question6 = question6,
            Question7 = question7,
            Question8 = question8,
            Question9 = question9,
            Question10 = question10,
            Interview_Id = id,
        };

       // ViewBag.ID = id;
        TempData["id"] = id;
        db.QuestionBlocks.Add(question);
        db.SaveChanges();

        return Json(new { Result = "Success", Message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);

    }

And try to update value in database like this in other

public ActionResult Update(string start, string end, string link)
    {

        ApplicationDbContext context = new ApplicationDbContext();
        var id = (int?)TempData["id"];
        IEnumerable<InvitationMail> customers = context.InvitationMails
            .Where(c => c.LinkStart == null)
            .Where(c => c.LinkEnd == null)
            .Where(c => c.Link == null)
            .Where(c=>c.Interview_Id==null)
            .AsEnumerable()
            .Select(c => {
                c.LinkStart = start;
                c.LinkEnd = end;
                c.Link = link;
                c.Interview_Id = id;
               return c;
            });


        foreach (InvitationMail customer in customers)
        {
            customer.Interview_Id = id;
            // Указать, что запись изменилась
            context.Entry(customer).State = EntityState.Modified;
        }

I set breakpoints and see that data in id. But it not writing to database.

Where is my fault?

thank's for help.

Here is my code:

public void SaveAs(string path) // path = "C:\\Users\\MyName\\Documents\\myImage.png"
{
    using (var file = System.IO.File.Open(path, FileMode.CreateNew))
    {
        // FileStream was created like this:
        // Stream FileStream = new MemoryStream(23201);
        FileStream.CopyTo(file); 
        file.Close();
    }
}

After calling the function, the file will be created but its size will be 0. This is the problem.

I searched for two days but couldn't get the solution. Any help will be appreciated. Thank you very much in advance.

Does chart.js able to display the difference between two values that are positioned on the same spot?

Currently in my chart, if there are more than one value that is on the same axis, the newer value will get "pinched" by the older one therefore I cannot see it.

Any workaround?

I have the below code to format the date on my views.

[DisplayName("Date Last Seen")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime? LostDate { get; set; }

It all works except that when I click the Edit view the current value of "LostDate" does not get rendered automatically.

How do I fix this?

Edit I have the code below for the edit view.

<div class="form-group">
    @Html.LabelFor(model => model.LostDate, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.LostDate, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.LostDate, "", new { @class = "text-danger" })
    </div>
</div>

I'm new on creating Web Api's and I need to pass a string to GetAsync method but I don't know what should I add to WebApiConfig file and how on GetAsync after the change. I've searched here but I've found nothing that helped me. Can anyone help me please?

My procedure:

private async void registrarServico(string nomeServico)
{
    using (HttpClient clientGet = new HttpClient())
    using (HttpClient clientSet = new HttpClient())
    {
        clientGet.BaseAddress = new Uri("api/ControladorServico/GetServico");
        var respostaGet = await clientGet.GetAsync("", nomeServico); //ERROR HERE!
    }
}

My WebApiConfig:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

My API method:

[HttpGet]
public IHttpActionResult GetServico(string nomeServico)
{
    try
    {
        return Ok(controladorServicoRep.CONTROLADOR_SERVICOSep.Get(d => d.NOME == nomeServico && d.MAQUINA == nomeMaquina).FirstOrDefault());
    }
    catch (Exception)
    {
        throw;
    }
}

Thank you.

Apologies if this is in the wrong category. I'm currently developing and application in ASP, due to my inexperience with ASP I'm worried about vulnerabilities that a user can exploit.

My application is being coded from scratch, no templates used or defaults from Visual Studio, completely blank projects. The user is greeted with a login page where depending on there user access in active directory depends on which pages the user can access.

The exploit I'm worried about is if the user will be able to commit a directory traversal and access a page in which they're not allowed to access and change critical information.

I'm afraid my inexperience has caught up with me. Could someone explain to me how I could limit the access to the user or, If I'm over thinking the process, correct me? Constructive criticism is accepted.

I want to store OleDbConnection object in session which has mode="StateServer" or mode="sqlserver" but while trying this I am getting error, which says- unable to serialize the session state. In stateserver and sqlserver mode asp.net will serialize the session state objects and as a result non-serializable objects or MarshalByRef are not permitted.

I am in middle of something, I want to compare only those values that are not Zero(0). like

 public ActionResult PropertyGrid(int drpCity, int Beds, int PropertyType, string Price)
        {

            var properties = dbEntity.tblProperties.Where(x => x.City == drpCity && x.Bedrooms == Beds && x.PropertyType == PropertyType).ToList();
            ViewBag.RecentProperties = dbEntity.tblProperties.Take(2).OrderByDescending(x => x.ID).ToList();

            ViewBag.CityList = GetCities();
            ViewBag.PropertyTypeList = GetPropertyTypes();
            return View(properties);
        }

Let say, If drpcity=0, it should not be included in query. then the query should be var properties = dbEntity.tblProperties.Where(x => x.Bedrooms == Beds && x.PropertyType == PropertyType).ToList();

If I check for each by if-else. Length of code will be too lenghtly. What will be the best way to do this.

I'm creating an ASP.NET MVC application for students which will learn languages. So, a student logs in and continues learning from the activity where the student stopped the last time. During the learning, after every page, I have to collect the points, count the correct and wrong answers and show the current result on every page. So I need a few parameters during the whole session, like:

  • CurrentActivityId
  • CurrentPageId
  • WrongAnswersCount
  • CorrectAnswersCount
  • CurrentResult

When the user clicks on a correct answer, I should call a function and increase the CorrectAnswersCount, for the wrong answers the same.

What is the best way to store those parameters? I already stored user data in claims, but I don't know if storing these learning parameters in claims is good to use? Can I store them somehow all together in one place, like in one class and save it into the session or is that a bad idea?

Thanks for the help!

When I am submitting form via Ajax, I have 2 ways of showing the user validation error messages:

1) If everything is ok return Json(new { Status = true }), if there are errors return View(model) in controller. And then on client side something like if (response.Status == undefined) $("#formWrapper).html(response) which will replace form with new one which contains error messages.

2) If everything is ok return Json(new { Status = true }), and if there are errors return Json(new { Status = false, Errors = errorList }) and then on client side go through errorList and append messages to elements.

Which one should I choose?

Note: I know I have client side validation and request wont be submitted at all if there are errors, but there are some things that need to be checked on backend and cant be put in client side validation, so I need mechanism to return info about validation errors from controller.

I just installed a fresh VS2013 on new machine (from Win7 to Win10), and I get all my cshtml views that are giving me errors.

I tried to

  • Reset my VS settings by using console devenv /resetsettings
  • Reset my settings by using Tools menu > Import and Export Settings > Reset all settings > Next > "No, just reset settings, overwriting all current settings" > Next > Finish.
  • remove the suo
  • repair my VS2013 install
  • clean all projects & build
  • Options>Text Editor > All languages > uncheck all "Statement completion", save, close, open and check them all

Next step is:

  • banging my head against the wall (haha)

It looks like it's a VS issue because when I take another web-project (a branch of this project) in TFS that run on another PC I get errors too.

It builds and it runs in localhost, but Razor give me error on Viewbag, Model, Html.LabelFor, etc.

When I clean project, no mistake but when I build it, I get all those "false" errors highlighted only in cshtml's...

Thanks to help

visual studio cshtml issue

EDIT I've MVC installed and copy local @ true MVC DLL

I need a function that says if the two strings "foo" and "bar" is true, I have to printout: "This is working"

Both strings has to be true before the text print. But how is the syntax for saying both has to be true: "foo" && "bar"?

if ((new List<string> { "foo", "bar" }).Contains(Model.Order.CancelPolicy))
        {
          <span>This is working</span> 
        }

This question already has an answer here:

I have list of Dates, and in controller i create code for DropDown list, in table i put dates like DATE format, also in model i configurired ad dd/MM/yyyy, in dropdown list i get dates included Time, but i need Just dates in List.

Code in Controller:

ViewBag.Datum = new SelectList(db.tbl_relacii.Where(x => x.DatumR >= date), "DatumR", "DatumR");

Code in View:

@Html.DropDownList("Datum", null, htmlAttributes: new { @class = "form-control" })

Model Code:

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
[DataType(DataType.Date)]
[Column(TypeName = "date")]
public DateTime DatumR { get; set; }

And here is data in database:

 data in database

How to take correct data in DropDown List

I am facing one unusual problem from so many days. I have one project in asp.net. Using vb.net for code. We have used bootstrap for design purpose as well. The problem is wherever I have used the text area in page and when that page loads, The "Enter" automatically comes in it. I am showing remaining characters below the text area. For example assume there are 50 characters to enter. and when page loads and I focus to text area, the remaining characters value become one less i.e 49 here. Because one "Enter" character is there. Not getting this at all. I have debugged the code. When page rendering finish and page appears, this happens. The image is here how it looksenter image description here For now When I save the text, I have removed this character. But I wanted to fix it permanently. Is that any issue because of bootstrap? Not getting this. Please any suggestions / solutions on this

Thank you

Im using MVC razor view

How do I group by my index view basen on Month in TrDate ??

My Index Controller:

private InvoiceMasterEntities db = new InvoiceMasterEntities();

    public ActionResult Index(int compID, string searchBy, string search, int? page, string sortBy)
    {
        ViewBag.SortDateParam = string.IsNullOrEmpty(sortBy) ? "Date desc" : "";
        ViewBag.SortStatusParam = sortBy == "Status" ? "Status desc" : "Status";

        var detail = db.DetailPengirimen.AsQueryable();

        if (searchBy == "CustID")
        {
            detail = detail.Where(b => b.CustID.Contains(search) || search == null);
        }
        else
        {
            detail = detail.Where(a => a.Customer.Fullname.Contains(search) || search == null);
        }

        detail = detail.Where(a => a.CompID == compID);

        switch (sortBy)
        {
            case "Date desc":
                detail = detail.OrderByDescending(a => a.TrDate);
                break;
            case "Status desc":
                detail = detail.OrderByDescending(a => a.Status.Status1);
                break;
            case "Status":
                detail = detail.OrderBy(a => a.Status.Status1);
                break;
            default:
                detail = detail.OrderBy(a => a.TrDate);
                break;
        }

        return View(detail.ToPagedList(page ?? 1, 10));
    }

My Index View:

@using PagedList;
@using PagedList.Mvc;

@model IPagedList<InvoiceTracker.Models.DetailPengiriman>

<h2>Couriers List</h2>

<p>
@Html.ActionLink("Insert Data", "Create", new { compID =    Request.QueryString["compID"] })
</p>

<p>
@using (Html.BeginForm("Index", "DetailPengiriman", new { compID = Request.QueryString["compID"] }, FormMethod.Post))
{
    <b>Search By:</b>
    @Html.RadioButton("searchBy", "CustID", true) <text>CustomerID</text>
    @Html.RadioButton("searchBy", "Fullname") <text>Customer Name</text>

    <br />

    @Html.TextBox("search")
    <input type="submit" value="Search" />
}
 </p>

 <table class="table">
<tr>
    <th>
        @Html.ActionLink("Transaction Date", "Index", new
   {
       sortBy = ViewBag.SortDateParam,
       searchBy = Request.QueryString["searchBy"],
       search = Request["search"],
       compID = Request["compID"]
   })
    </th>
    <th>
        CustomerID
    </th>
    <th>
        Customer Name
    </th>
    <th>
        Invoice
    </th>
    <th>
        Nama Penerima
    </th>
    <th>
        Status Penerima
    </th>
    <th>
        @Html.ActionLink("Status", "Index", new
   {
       sortBy = ViewBag.SortStatusParam,
       searchBy = Request.QueryString["searchBy"],
       search = Request["search"],
       compID = Request["compID"]
   })
    </th>
    <th>
        Status Date
    </th>
    <th>
        Image
    </th>
    <th>Actions</th>
</tr>

 @foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.TrDate)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Customer.CustID)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Customer.Fullname)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.InvoiceNo)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.NamaPenerima)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.StatusPenerima)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Status.Status1)
    </td>   
    <td>
        @Html.DisplayFor(modelItem => item.Status.StatDate)
    </td>      
    <td>           
        @if (item.Image.Image1 != null)
        {
            var base64 = Convert.ToBase64String(item.Image.Image1);
            var imgSrc = ($"data:image/png;base64,{base64}");
            <img src="@imgSrc" width="50" height="50" 
            onMouseOut="zoomtoggle('50','50px','50px','50px',this);"  
                  onMouseOver="zoomtoggle('400px','200px','400px','200px',this);"/>
        }
        else
        {
            <text> No Image Available</text>
        }
    </td>        
    <td>
        @Html.ActionLink("Edit", "Edit", new
   {
       id = item.TransID,
       custID = item.CustID,
       statID = item.StatusID,
       imgID = item.ImageID,
       invoNo = item.InvoiceNo
   }) |
        @Html.ActionLink("Delete", "Delete", new
   {
       id = item.TransID,
       custID = item.CustID,
       statID = item.StatusID,
       imgID = item.ImageID,
       invoNo = item.InvoiceNo
   })
    </td>
</tr>
 }

 </table>

 @Html.PagedListPager(Model, page => Url.Action("Index", new
 {
page,
searchBy = Request.QueryString["searchBy"],
search = Request.QueryString["search"],
sortBy = Request["sortBy"],
compID = Request["compID"]
 }),
new PagedListRenderOptions() { Display = PagedListDisplayMode.IfNeeded })

I want the view listed the data from database group by month in TrDate attribute TrDate data are from datetime.now TrDate data type is DateTime