I am porting a windows desktop application to an ASP.NET MVC application. I have a bunch of tables in the database that I am able to create controllers with to generate views and it works fine. I want to create a page to display all the names that have a certain column that is set to false. Because there is no table that stores this data I have to manually query for the result using linq. So what I have done is ignored the creation of the model and created the controller.

private raceEntities db = new raceEntities();

    // GET: Registrants
    public ActionResult Index()
    {
        var registrants = (from per in db.people
                          join personorgrole in db.personorganizationroles on per.PersonID equals personorgrole.PersonID
                          join personeve in db.personevents on personorgrole.PersonOrganizationRoleID equals personeve.PersonOrganizationRoleID
                          join eventcla in db.eventclasses on personeve.RaceEventID equals eventcla.RaceEventID
                          join racecla in db.raceclasses on eventcla.RaceClassID equals racecla.RaceClassID
                          join personeventcla in db.personeventclasses on eventcla.EventClassID equals personeventcla.EventClassID
                          where personorgrole.PersonID == 90946
                          select new { per.FirstName, per.LastName }).ToList();
        ViewBag.Res = registrants;

        return View();
    }

and in the view i have this code

@model IEnumerable<IDFWebApp.Controllers.Custom.peopleController>
@{
    ViewBag.Title = "Index";
}

<ul>
    @foreach (var r in ViewBag.Res)
    {
        <li>
            @r
        </li>
    }
</ul>

Currently this query is for testing purposes to see if the data will show on the page, but it doesn't display the names.

After trying, browsing, testing for hours I still don't get it. Here is the problem:

I've started the project with the ASP.NET Web Site Razor v3 template in Visual Studio Community 2013. Why the heck this code causes the latest (desktop) browsers NOT to load the images. As you see, the HTML string is set to the variable and then I try to output it as HTML code:

@{ var q = "<img src=\"~/Images/Arrow-Back-iconL.png\" alt=\"galerija puščica levo\" id=\"puscicaL_0\" class=\"puscica puscical\" style=\"opacity:1\" />";
 }
 @Html.Raw(q)
 @(new HtmlString(q))

But this code of course enables images to load:

<img src="~/Images/Arrow-Back-iconL.png" alt="galerija puščica levo" id="puscicaL_0" class="puscica puscical" style="opacity:1" />

I have Website in my localhost (IIS) on Windows 8.1, I can access it from:

It binded to "All Unassigned" and Port 80 and Localhost.

But I can't access this website from another PC (windows 7) in same network.

Please notice that:

  • Both are connected to same wireless modem
  • I have Eset SmartSecurity on both of PCes and firewall are disabled.
  • I can ping both in cmd like: 192.168.1.50
  • In Windows 7 PC port 0.0.0.0:80 is bonded (I check it with netstat -na and result is: TCP 0.0.0.0:80 0.0.0.0:0 LISTENING)
  • In Windows 7 PC Telnet 192.168.1.50 80 connected correctly
  • In Windows 7 Pc also I installed IIS 7
  • Security Permission of website folder

I'm really confused and don't know what to do!!!

What difference between node.js non-blocking model and ASP.NET MVC non-blocking async/await with Tasks ? i meant they successfully solving the same problem in the same way or i missed something ? I think other framework have had the same solution before node ?

I have seen examples like this

public IHttpActionResult GetProduct(int id)
{
    Product item = repository.Get(id);
    if (item == null)
    {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
    return Ok(item);
}

But I have also imagine this is an option

public IHttpActionResult GetProduct(int id)
{
    Product item = repository.Get(id);
    if (item == null)
    {
        return NotFound();
    }
    return Ok(item);
}

Is there an advantage to throwing an exception or simply returning a NotFound (IHttpActionResult instance)?

I know there are stages in the response / request pipeline where either of these results can be handled, like this for the first example

public class NotFoundExceptionFilterAttribute : ExceptionFilterAttribute 
{
    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is NotFoundException)
        {
            // Do some custom stuff here ...
            context.Response = new HttpResponseMessage(HttpStatusCode.NotFound);
        }
    }
}

...

GlobalConfiguration.Configuration.Filters.Add(
    new ProductStore.NotFoundExceptionFilterAttribute());

Question rebuild.

I have a html table:

<div class="form-group">
    @Html.Label("Lista pytan:", new { @class = "col-md-2 control-label" })
    <table id="questionTable" border="0">
        <tbody id="questionTableBody">
        </tbody>
    </table>
</div>

Which is builded dynamically via javascript AddRow() function called onclick:

function addRow(table, value)
    {
        var tab = document.getElementById(table);
        var rowCount = tab.rows.length;
        var row = tab.insertRow(rowCount);
        var cell1 = row.insertCell(0);
        var lp = document.createElement("label");
        lp.name = "lblLp[]";
        lp.className = "col-md-2 control-label";
        lp.textContent = "" + (rowCount + 1);
        cell1.appendChild(lp);
        var cell2 = row.insertCell(1);
        var element1 = document.createElement("label");
        element1.name = "lbl[]";
        element1.className = "col-md-2 control-label";
        element1.textContent = document.getElementById(value).value;
        cell2.appendChild(element1);
        var cell3 = row.insertCell(2);
        var element2 = document.createElement("input");
        element2.type = "button";
        element2.name = "btn[]";
        element2.value = "Usun";
        element2.className = "btn btn-default";
        element2.addEventListener('click', function () {                
            deleteRow(table, row.rowIndex);
        });
        cell3.appendChild(element2);
    }

Based on this table i want to create a model right before calling

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Add(AddQuestionnaireModel model) 

in my controller.

My model looks like this:

public class AddQuestionnaireModel
{
    public QuestionnaireServiceReference.Questionnaire Questionnaire {get;set;}

    public AddQuestionnaireModel()
    {
        Questionnaire = new QuestionnaireServiceReference.Questionnaire();
    }
}

And Questionnaire is an object generated form EntityFramework:

public partial class Questionnaire
{
    public Questionnaire()
    {
        this.Question = new HashSet<Question>();
    }

    public long questionnaire_id { get; set; }
    public string name { get; set; }

    public virtual ICollection<Question> Question { get; set; }
}

Most important thing is that Questionnaire contain list of objects. How to via Ajax or Javascript fill a Model in my View?

I have add onclick funkction to my button submit button, named: fillQuestionnaire().

Can you help me build my fillQuestionnaire() javascript funkction? (or ajax if u have other ideas)

I am running ASP.net with Razor syntax on Windows 7 IIS7 version 7.

But IIS give me error. HTTP Error 404.17 - Not Found

Note: i have already installed visual studio 2005 version on my system.

<!DOCTYPE html>

<html lang="en">
<head>
     <meta charset="utf-8" />
     <title>Web Pages Demo</title>
</head>
<body>
     <h1>Hello Web Pages</h1> 
     <p>The time is @DateTime.Now</p>
</body>
</html>

I have a controller which displays user profiles the Action for showing a profile is just under Index : its /User/123 to show user 123. This is set on route map like this:

routes.MapRoute(
            name: "User",
            url: "User/{id}",
            defaults: new {controller = "User", action = "Index", id = UrlParameter.Optional}
            );

Now my controller looks something like this:

public class UserController : Controller
{
    [Authorize]
    public ActionResult Index(int id)
    {
        *edited out for simplicity*
        return View(model);
    }

    [Authorize]
    [HttpPost]
    public ActionResult Follow(int id)
    {
        *edited out for simplicity*
        return RedirectToAction("Index", "User", new { id });
    }
}

And my web form:

using (Html.BeginForm("Follow", "User", FormMethod.Post))
            {
                <input type="submit" value="Follow!" class="btn btn-success" />
            }

Now the GET works perfectly but when I submit the POST it isnt handing over the user id from the url /user/123.

Do I need to perform an extra action in the Html.BeginForm if I am going from a GET on Index to a POST on Follow in order for it to hand over the {id} ?

Thanks in advanced for any advise!

I have this code on my Create view.

<div class="col-lg-6">
        <!--Ingredients-->
        @Html.LabelFor(model => model.Ingredients, htmlAttributes: new { @class = "control-label col-md-2" })<br />
        <textarea class="form-control" id="ingredients" rows="20" onsubmit="PopulateIngredients()"></textarea>
    </div>


    <script>
        function PopulateIngredients()
        {
            var ingredientArray = document.getElementById('ingredients').val().split('/n');
            if (ingredientArray.length !=0)
            {
                for (i = 0; i < ingredientArray.length; i++)
                {
                    @(Model.Ingredients).Add(ingredientArray[i]);
                }

            }

        }
    </script>

When the page is loading I get an error in the script saying "Object reference not set to an instance of an object." at this line;

    @(Model.Ingredients).Add(ingredientArray[i]);

Two problems exist. One is that I should be seeing the model.Ingredients IEnumerable object. Two is that his script shouldn't run until the submit button is clicked.

What am I doing wrong? I have to use a text area for input so I have to split it and add it to the ingredient list before it is posted back to the controller where it is handled as a list of ingredient objects. I did not include the classes for brevity.

Paging is fine when display results at first, query return data from search conditions, but when i go to some other page of paging recordset for example second, it shows me all the data from query without search conditions. Here is my code. Please help

connStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & _
                                                Server.MapPath("db/bbs.mdb")

                                    Dim rs
                                    Set rs = Server.CreateObject("ADODB.Recordset")

                                    rs.PageSize = 5
                                    rs.CacheSize = 5
                                    rs.CursorLocation = adUseClient

                                    If mode = "form1" then
                                        SQL = "SELECT * FROM BuyABusiness WHERE refno = '"& referenceNo &"' OR Category LIKE '%"& referenceNo &"%'"
                                    ElseIf mode = "form2" then
                                        SQL = "SELECT * FROM BuyABusiness WHERE "& SQL1 &"  ID <> 0 ORDER BY uploadDate DESC "
                                    ElseIf mode = "form3" then
                                        SQL = "SELECT * FROM BuyABusiness ORDER BY uploadDate DESC "
                                    End If

                                    rs.Open SQL, connStr, adOpenForwardOnly, adLockReadOnly, adCmdTableDirect

                                    Dim abspage, pagecnt
                                    abspage = rs.AbsolutePage
                                    pagecnt = rs.PageCount

                                    If Not rs.EOF Then

                                        If Len(Request("pagenum")) = 0  Then
                                            rs.AbsolutePage = 1
                                        Else
                                            If CInt(Request("pagenum")) <= rs.PageCount Then
                                                rs.AbsolutePage = Request("pagenum")
                                            Else
                                                rs.AbsolutePage = 1
                                            End If
                                        End If
                                        Response.Write "PageCount : " & rs.PageCount & "<br>" & vbcrlf
                                        Response.Write "Absolute Page : " & rs.AbsolutePage & "<br>" & vbcrlf
                                        Response.Write "Total number of records : " & rs.RecordCount
                                        Response.Write "<br><br>" & vbcrlf
                                        Response.Write "Now showing page " & rs.AbsolutePage & " of pages " & rs.PageCount

                                        'Dim fldF, intRec
                                        Response.Write "<table border=0 align=center cellpadding=0 cellspacing=0 width='80%'><thead>"

                                        'For Each fldF in rs.Fields
                                            'Response.Write "<td class='tdfontB'>" & fldF.Name & "</td>"
                                        'Next

                                        Response.Write "</tr></thead><tbody>"

                                        Response.Write "<div align=""center"">" & vbcrlf
                                        Response.Write "<a href="""
                                        Response.Write Request.ServerVariables("SCRIPT_NAME")
                                        Response.Write "?mode="& mode &"&pagenum=1""><b>First Page</b></a>"
                                        Response.Write "    |   "

                                        For i = 1 to rs.PageCount
                                                    response.write "<a href='buyabusiness3.asp?mode="& mode &"&pagenum="& i &" '>"& i & "</a>"
                                                    Response.Write "    |   "
                                        Next

                                        Response.Write "<a href=""" & Request.ServerVariables("SCRIPT_NAME")
                                        Response.Write "?mode="& mode &"&pagenum=" & pagecnt & """><b>Last Page</b></a>"
                                        Response.Write "</div>" & vbcrlf

                                        For intRec=1 To rs.PageSize
                                            'If Not rs.EOF Then
                                            '   Response.Write "<tr>"
                                            '   For Each fldF in rs.Fields
                                            '       Response.Write "<td class='tdfont'>" & fldF.Value & "</td>"
                                            '   Next
                                            '   Response.Write "<tr>"
                                            '   rs.MoveNext
                                            'End If

                                            If Not rs.EOF then

                                                response.write "<tr valign='top' bgcolor='#cedada' height='20'>"
                                                response.write "    <td width='5'></td><td class='tdfont' width='100'><b>Ref No</b></td><td width='10'></td><td class='tdfont'>"& rs.fields("refNo") &"</td>"
                                                response.write "    <td rowspan=4 align=right>"
                                                response.write "        <table cellspacing='0' cellpadding='0'>"
                                                response.write "            <tr>"
                                                                            If rs.fields("status") = "Now Available" Then
                                                                                response.write "<td><img src='images/NowAvailable.jpg'></td>"
                                                                            ElseIF rs.fields("status") = "Coming Soon" Then
                                                                                response.write "<td><img src='images/ComingSoon.jpg'></td>"
                                                                            ElseIF rs.fields("status") = "Sold" Then
                                                                                response.write "<td><img src='images/sold.jpg'></td>"
                                                                            End If
                                                response.write "            </tr>"
                                                response.write "        </table>"
                                                response.write "    </td>"
                                                response.write "</tr>"
                                                response.write "<tr valign='top' bgcolor='#cedada' height='20'>"
                                                response.write "    <td width='5'></td><td class='tdfont' width='100'><b>State</b></td><td width='10'></td><td class='tdfont'>"& rs.fields("state") &"</td>"
                                                response.write "</tr>"
                                                response.write "<tr valign='top' bgcolor='#cedada' height='20'>"
                                                response.write "    <td width='5'></td><td class='tdfont' width='100'><b>Location</b></td><td width='10'></td><td class='tdfont'>"& changeapos(rs.fields("location")) &"</td>"
                                                response.write "</tr>"
                                                response.write "<tr valign='top' bgcolor='#cedada' height='20'>"
                                                response.write "    <td width='5'></td><td class='tdfont' width='100'><b>Category</b></td><td width='10'></td><td class='tdfont'>"& rs.fields("category") &"</td>"
                                                response.write "</tr>"
                                                response.write "<tr valign='top' bgcolor='#cedada'>"
                                                response.write "    <td width='5'></td><td class='tdfont' colspan='4' height='10'></td>"
                                                response.write "</tr>"
                                                response.write "<tr valign='top' bgcolor='#cedada' height='20'>"
                                                response.write "    <td width='5'></td><td class='tdfont' colspan='4'>"& changeapos(rs.fields("description")) &"</td>"
                                                response.write "</tr>"
                                                response.write "<tr valign='top' bgcolor='#cedada' height='20'>"
                                                response.write "    <td width='5'></td><td class='tdfont' colspan='4' height='10'></td>"
                                                response.write "</tr>"
                                                response.write "<tr valign='top' bgcolor='#cedada' height='20'>"
                                                response.write "        <td width='5'></td><td class='tdfont' width='100' align='left'><b>Profit</b></td><td width='1'></td><td class='tdfont' width='300' align='left'>"

                                                                SQL = "SELECT * FROM takings "
                                                                set rs2 = conn.execute(SQL)

                                                                While not rs2.EOF
                                                                    If rs.fields("netprofit") >= rs2.fields("minValue") And rs.fields("netprofit") <= rs2.fields("maxValue") Then
                                                                        response.write rs2.fields("takings")
                                                                    End If
                                                                rs2.MoveNext
                                                                Wend
                                                                rs2.close
                                                                set rs2 = nothing

                                                response.write "        </td><td width='5'></td>"
                                                response.write "    </tr>"
                                                response.write "<tr valign='top' bgcolor='#cedada' height='20'>"
                                                response.write "        <td width='5'></td><td class='tdfont' width='100' align='left'><b>Price</b></td><td width='1'></td><td class='tdfont' width='300' align='left'>RM "& FormatNumber(rs.fields("price"),0) &"</td><td width='5'></td>"
                                                response.write "    </tr>"
                                                response.write "<tr valign='top' bgcolor='#cedada'>"
                                                response.write "    <td colspan='5'>&nbsp;</td></tr>"
                                                response.write "<tr valign='top' bgcolor='#cedada'>"
                                                response.write "    <td width='5'></td><td class='tdfont' width='100'></td><td width='10'></td><td class='tdfont'><a href='buyabusiness2.asp?id="& rs.fields("id") &"'><img src='images/btnMoreInfo.gif' border=0></a></td><td></td>"
                                                                    '<input type=button value='more info' class=btnRed>
                                                response.write "</tr>"
                                                response.write "<tr valign='top' bgcolor='#cedada'>"
                                                response.write "    <td class='tdfont' colspan='5' height='5'></td>"
                                                response.write "</tr>"
                                                response.write "<tr valign='top' bgcolor='#e9e9e7' height='20'>"
                                                response.write "    <td class='tdfont' colspan='5'></td>"
                                                response.write "</tr>"
                                                rs.movenext
                                            End If
                                        Next
                                        Response.Write "</tbody></table><p>"

If Len(Request("pagenum")) = 0 Then rs.AbsolutePage = 1 Else If CInt(Request("pagenum")) <= rs.PageCount Then rs.AbsolutePage = Request("pagenum") Else rs.AbsolutePage = 1 End If End If 'Response.Write "PageCount : " & rs.PageCount & "
" & vbcrlf 'Response.Write "Absolute Page : " & rs.AbsolutePage & "
" & vbcrlf 'Response.Write "Total number of records : " & rs.RecordCount 'Response.Write "

" & vbcrlf Response.Write "Now showing page " & rs.AbsolutePage & " of pages " & rs.PageCount

                                        Response.Write "<div align=""center"">" & vbcrlf
                                        Response.Write "<a href="""
                                        Response.Write Request.ServerVariables("SCRIPT_NAME")
                                        Response.Write "?mode="& mode &"&pagenum=1""><b>First Page</b></a>"
                                        Response.Write "    |   "

                                        For i = 1 to rs.PageCount
                                            response.write "<a href='buyabusiness3.asp?mode="& mode &"&pagenum="& i &" '>"& i & "</a>"
                                            Response.Write "    |   "
                                        Next

                                        'Response.Write "   |   "
                                        Response.Write "<a href=""" & Request.ServerVariables("SCRIPT_NAME")
                                        Response.Write "?mode="& mode &"&pagenum=" & pagecnt & """><b>Last Page</b></a>"
                                        Response.Write "</div>" & vbcrlf


                                    Else
                                        Response.Write "No records found!"  
                                    End If

                                    rs.Close
                                    Set rs = Nothing

I copied the following web.config from the github paypal net sdk page, but got an error saying could not find schema information for the element ;Paypal'. Is there something wrong with my web.config syntax (this is for an asp.net website):

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
  <configSections>
    <section name="paypal" type="PayPal.SDKConfigHandler, PayPal" />
  </configSections>

  <!-- PayPal SDK settings -->
  <paypal>
    <settings>
      <add name="mode" value="sandbox"/>
      <add name="clientId" value="_client_Id_"/>
      <add name="clientSecret" value="_client_secret_"/>
    </settings>
  </paypal>
</configuration>

I am running ASP.net with Razor syntax on Windows 7 IIS7 version 7.

But IIS give me error. HTTP Error 404.17 - Not Found

Note: i have already installed visual studio 2005 version on my system.

<!DOCTYPE html>

<html lang="en">
<head>
     <meta charset="utf-8" />
     <title>Web Pages Demo</title>
</head>
<body>
     <h1>Hello Web Pages</h1> 
     <p>The time is @DateTime.Now</p>
</body>
</html>

In my IHttpModule I do HttpContext.Current.RewritePath from / to www.website.com/userid/Index.aspx. userid is unknown in advance, I get it from DB. The resulting page is displayed correctly, but there is a problem.

I have another IHttpModule. It is not called when I go www.website.com. If I manually go www.website.com/userid/Index.aspx in browser - it is called.

Of course I can remove preCondition="managedHandler" in web.config for that second IHttpModule, but in that case module will do a lot of unnecessary calculations for every static file.

Any ideas? How can I enable second IHttpModule for www.website.com url and every "managed" page in my website?

I spent way too much time solving this simple problem than I should. Therefore, I would like SO to look at this, because I do not get why it does not work. I am used to change CSS properties with jQuery, but in this particular case it doesn't work.

So this is my function that is supposed to change the background colour of table cells:

$("table#project_table td").click(function () {     //function_td
    var currProjectVar = "#MainContent_CurrProject";
    if ($(currProjectVar).val() == "None") {
        $(currProjectVar).val($(this).attr('id'));
        $(this).css("background-color", "red");
    } else {
        $("table#project_table td#" + $(currProjectVar).val()).css("background-color", "blue");
        $(currProjectVar).val($(this).attr('id'));
        $(this).css("background-color", "red");
    }
})

It does change background-color to red, but not to blue. When that line that changes colour to blue is executed, nothing happens. The cell is still red.

This is the code that defines the table:

<table id="project_table">
    <tr>
        <td id="0">Project0</td><td id="1">Project1</td><td id="2">Project2</td><td id="3">Project3</td><td id="4">Project4</td><td id="5">Project5</td><td id="6">Project6</td>
    </tr>
    <tr>
        <td id="7">Project7</td><td id="8">Project8</td><td id="9">Project9</td><td id="10">Project10</td><td id="11">Project11</td><td id="12">Project12</td>
    </tr>
</table>

This is the hidden field that I use to store the current chosen project:

<input type="hidden" name="ctl00$MainContent$CurrProject" id="MainContent_CurrProject" value="None">

There are no problems with marking new cells red or changing the value of the current project. I cannot make earlier cells blue though. What am I doing wrong?

Btw: do not know, whether this is important to mention, but this script runs in an ASP.NET website.

I am trying to use @HTML.DisplayFor in @ForEach statement but not successful.

The following is my existing code:

@foreach (var cost in Model.CustomerCost)
{
    <tr>
        <td>@cost .CustomerName</td>
        <td>@(cost.Cost!= 0 ? string.Format("{0:C}", cost.Cost) + " USD" : "-")</td>
    </tr>
}

However, i am trying to replace the following line of code

<td>@(cost.Cost!= 0 ? string.Format("{0:C}", cost.Cost) + " USD" : "-")</td>

with

@HTMLDisplayFor

<td>@(cost.Cost!= 0 ? Html.DisplayFor(model => model.CustomerCost[cost].Cost + "USD":"-")</td>

What is wrong in @HTML.DisplayFor syntax?

i have a view as the follows :

<div style="text-align:center;">

@using (Ajax.BeginForm("GetEmps", "Employee", new AjaxOptions { UpdateTargetId = "Emps", HttpMethod = "Post", InsertionMode = InsertionMode.Replace }))
{
    @Html.DropDownList("option", (IEnumerable<SelectListItem>)ViewBag.ListOfEmpType, new { onchange = "this.form.submit();" })
}    

</div>

<br /><hr /><br />

<div id="Emps" style="text-align:center;"></div>

my controller action is :

[HttpPost]
public PartialViewResult GetEmps(int option)
{
    List<Employee> Empls = GE.Employees.Where(e => e.Emp_Type_ID == option).ToList();
    return PartialView("_ShowEmpTable", Empls);
}

my partial view is :

@model IEnumerable<Gym.Models.Employee>

<script src="~/Scripts/jquery-2.1.3-vsdoc.js"></script>
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script src="~/Scripts/jquery-2.1.3.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

<table id="tblBlah">
<tr>
    <th>Name</th>
    <th>Telephone</th>
    <th>Email</th>
</tr>
@foreach (var item in Model)
{
<tr onmouseover="GetRowIndex(this)">
     <td>
        <div>@item.Employee_Name</div>
     </td>
     <td>
        <div>@item.Employee_Tel</div>
     </td>
     <td>
        <div>@item.Employee_Email</div>
     </td>
</tr>
}
</table>

<script>
var RowIndex;
function GetRowIndex(x) {
    RowIndex = x.rowIndex;
}
</script>

the problem is :
when ajax form executed the UpdateTargetId not replace only the target "Emps"
it replace all view page
and change all route URL from
http://localhost:63367/Employee/Index
to
http://localhost:63367/Employee/GetEmps

i don't know why partial view remove all essential view .. please help me

I have modifying the existing multilingual asp.net website. I have made changes as i want and it's working fine in local server.But when i deploy it on server , it shows like index01.html?aspxerrorpath=/foldername/index.aspx

how to resolve this problem. strong text

I am facing problem with Recaptcha 2.0. Its working fine untill I click the button to check for validation. But it always executing the else block and showing "Validation failed.".Am I missing something.Please Help.

In aspx,

  <head runat="server">
    <title></title>
    <script type="text/javascript" src="https://www.google.com/recaptcha/api.js"></script>
</head>
<body>
    <form id="form1" action="?" method="post" runat="server">
        <div>
            <div class="g-recaptcha" data-sitekey="Public_Key"></div>
            <asp:Button ID="ButtonCheck" runat="server" Text="Check" OnClick="ButtonCheck_Click" />
            <asp:Label ID="LabelMessage" runat="server" ></asp:Label>
        </div>
    </form>
</body>

Then a classs,

public class MyObject
    {
        public string success { get; set; }
    }

Then In Code Behind File,

protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void ButtonCheck_Click(object sender, EventArgs e)
        {
            if(Page.IsValid)
            {
                if(CheckValidation())
                {
                    LabelMessage.Text = "You are ready to go.";
                }
                else
                {
                    LabelMessage.Text = "Validation Failed.";
                }
            }
        }
        public bool CheckValidation()
        {
            string Response = Request["g-recaptcha-response"];
            bool Valid = false;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret=Private_Key &response=" + Response);
            try
            {
                using(WebResponse webResponse=request.GetResponse())
                {
                    using(StreamReader streamReader=new StreamReader(webResponse.GetResponseStream()))
                    {
                        string jasonResponse = streamReader.ReadToEnd();
                        JavaScriptSerializer js = new JavaScriptSerializer();
                        MyObject data = js.Deserialize<MyObject>(jasonResponse);
                        Valid = Convert.ToBoolean(data.success);
                    }
                }
                return Valid;
            }
            catch(WebException ex)
            {
                throw ex;
            }
        }

Alright I am a bit of a newb when it comes to ASP.net. I am used to PHP.

Anyway, I am working on a website that is connected to my server via ftp. Everything is working fine, except I just added some classes in the App_Code folder. I cannot access those classes when I go to the page on the web.

I was researching a bit and everyone said I needed to publish the website. Well I did that, and it completely broke. I had to restore from a backup and lost a lot. My own fault though.

The classes work if I am using them on a local web site, but not on the web. Any guidance here? I've tried moving the App_Code folder around with no luck.

I have two gridviews in asp.net separated using Ajax's tab container. In one button click event, I want the two gridviews to be populated using a datasource from two different stored procedures.

First gridview - detailed summary of sales per tenant

Second gridview - Consolidated sales group per date

Here's the code

        SqlCommand cmd = new SqlCommand("spDSRDetailed", con);
        cmd.CommandTimeout = 120;
        cmd.CommandType = System.Data.CommandType.StoredProcedure;


        cmd.Parameters.AddWithValue("@dateFrom", txtdatefrom.Text);
        cmd.Parameters.AddWithValue("@dateTo", txtdateto.Text);
        cmd.Parameters.AddWithValue("@Location", hdnLoc.Value);
        cmd.Parameters.AddWithValue("@RP", hdnRP.Value);



        try
        {
            con.Open();
            grdDailySalesReport.EmptyDataText = "No Records Found";
            grdDailySalesReport.DataSource = cmd.ExecuteReader();

            grdDailySalesReport.DataBind();


        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
            con.Dispose();
        }

This code works only with one gridview, I know it is possible to do this using SQLDatasource, But that method is not my option because I have used a complex SQL queries and not ideal to do it using SQLDATASOURCE.SELECTCOMMAND.

I tried this and it gives me this error

There is already an open DataReader associated with this Command which must be closed first.

   SqlCommand cmd = new SqlCommand("spDSRDetailed", con);
        cmd.CommandTimeout = 120;
        cmd.CommandType = System.Data.CommandType.StoredProcedure;

        SqlCommand cmd2 = new SqlCommand("spDSRConso", con);
        cmd2.CommandTimeout = 120;
        cmd2.CommandType = System.Data.CommandType.StoredProcedure;



        cmd.Parameters.AddWithValue("@dateFrom", txtdatefrom.Text);
        cmd.Parameters.AddWithValue("@dateTo", txtdateto.Text);
        cmd.Parameters.AddWithValue("@Location", hdnLoc.Value);
        cmd.Parameters.AddWithValue("@RP", hdnRP.Value);

        cmd2.Parameters.AddWithValue("@dateFrom", txtdatefrom.Text);
        cmd2.Parameters.AddWithValue("@dateTo", txtdateto.Text);
        cmd2.Parameters.AddWithValue("@Location", hdnLoc.Value);
        cmd2.Parameters.AddWithValue("@RP", hdnRP.Value);




        try
        {
            con.Open();
            grdDailySalesReport.EmptyDataText = "No Records Found";
            grdDailySalesReport.DataSource = cmd.ExecuteReader();
            grdDailySalesReport.DataBind();


            grdDSRConso.EmptyDataText = "No Records Found";
            grdDSRConso.DataSource = cmd2.ExecuteReader();
            grdDSRConso.DataBind();



        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
            con.Dispose();
        }

I tried to fix the code below as I am getting this error message:

Object reference not set to an instance of an object.

Next to this line:

DAsearchads.SelectCommand.Parameters.AddWithValue("@Wtags", result.Value); 

Can you please help me to fix this code and make run smoothly

HttpCookie intoo = Request.Cookies.Get("into");
HttpCookie result = Request.Cookies.Get("Searchfor");
HttpCookie cookie = Request.Cookies.Get("Location");
//string result = Request.QueryString["Searchfor"];

if (cookie["Location"] == null)
{
    if (Request.QueryString["intoo"] == "Ads")
    {
        if (Request.QueryString["Searchfor"] != null)
        {
            using (SqlConnection srcadshsql = new SqlConnection(sc))
            {
                srcadshsql.Open();

                SqlDataAdapter DAsearchads = new SqlDataAdapter(
                    @"SELECT [AdsID], [AdsDate], [AdsPrice], [AdsTit], SUBSTRING([AdsDesc],1,50) as AdsDesc,
                     [Section], [Category], [Wtags], [Country], 
                     [State], [City],[Img1] FROM [ads] WHERE (([Country] = @Country) AND ([Wtags] = @Wtags))", sc);

                DataSet DSsrchads = new DataSet();

                DAsearchads.SelectCommand.Parameters.AddWithValue("@Country", cookie.Value);
                DAsearchads.SelectCommand.Parameters.AddWithValue("@Wtags", result.Value);

                DAsearchads.Fill(DSsrchads);
                resultshowlistview.DataSource = DSsrchads.Tables[0];
                resultshowlistview.DataBind();
                SrchMultiView.ActiveViewIndex = 0;
            }
        }
    }
}