I use ASP.NET, and I want generate Meta tags for last-modified:

<head>
<meta http-equiv="last-modified" content="2013-10-23@17:23:00 UTC" />
</head>

I use this code in the page:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (this.IsPostBack) return;


        // .. and set last modified in the date format specified in the HTTP rfc.
        //  <meta http-equiv="last-modified" content="2013-10-23@17:23:00 UTC" />
        var value = DateTime.Now.ToUniversalTime().ToString("R");
        Response.AddHeader("Last-Modified", value);
        Response.AppendHeader("Last-Modified", value);

        Response.Cache.SetLastModified(DateTime.Now);
    }

But nothing generate in the head.

Any suggestions?

I created a simple ASP.NET page using C# where a user enters a parameter, clicks on a button and an SSRS report is run and displayed within the webpage. However, i would like the report to open in a new window instead of embedded in the ASPX page.

Here is my current code now:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Reporting.WebForms;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        try
        {
            string AccountNumber = AcctNo.Text;
            ReportViewer.ProcessingMode = ProcessingMode.Remote;
            ReportViewer.ServerReport.ReportServerUrl = new Uri(@"http://johnssrsd04/ReportServer_SSRS2008DEV01");
            ReportViewer.ServerReport.ReportPath = "/Client Metrics POC/Reports/ClientMetricsDownload_POC";
            ReportViewer.ServerReport.Refresh();
            ReportParameter[] reportParameterCollection = new ReportParameter[1]; //Array size describes the number of paramaters.
            reportParameterCollection[0] = new ReportParameter();
            reportParameterCollection[0].Name = "paraAcctNo"; //Give Your Parameter Name
            reportParameterCollection[0].Values.Add(AccountNumber); //Pass Parametrs's value here.
            ReportViewer.ServerReport.SetParameters(reportParameterCollection);
            ReportViewer.ServerReport.Refresh();
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }
}

Is there a way to change it to open the SSRS report in an new window?

Looking at tutorials for self-hosted OWIN apps, the tutorials all point to using an ApiController. This code works:

public class MapController : ApiController
{
    // Get /map
    public async Task<HttpResponseMessage>  Get()
    {
        return await Task.Run(() => {
            string html = File.ReadAllText("./Client/html/MapExample.html");
            HttpResponseMessage response = new HttpResponseMessage
            {
                Content = new StringContent(html)
            };
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
            return response;
        });
    }
}

And this seems to work... Why would I want to extend Controller vs ApiController?

I actually don't have access to the Controller class so far as I can tell with the OWIN libraries...

I want to pass comma in input field to server using input arrays. The server gets comma-separated input values from array of inputs and if an input contains comma as a text then it considers that comma as separator.

Example:

HTML Code:

<input type="text" name="abc[]" value="1,2" />
<input type="text" name="abc[]" value="3,4" />

ASP.NET Server side code:

string[] ArrayOfInputs = Request.Form["abc[]"].Split(',');

gives me "1,2" as ["1", "2"] etc.

How to avoid this and get ["1,2", "3,4"]

I want to display some li tags only if the strings received from the model contains text. Right now my list looks like this:

ul class="ul-with-bullets">
                @{
                    for (int i = 1; i < 6; i++)
                    {
                        if (@Model.GetValue("punkt" + i) != "")
                        {
                            <li>@Model.GetValue("punkt" + i)</li>
                        }
                    }
                }
</ul>

The Model contains 5 properties (punkt1, punkt2, etc.), and I only want to display a li tag for these that contain a value (string). My above code still displays all the li tags on the page. I tried using string.Empty instead of "" as well but with the same result.

For reference, this is a partial view for the Archetype property editor in Umbraco. Each property in the fieldset is a textstring.

I need to store both the name and the id of the option the user chooses in my SQL Database. Right now I am only storing the Id, by setting the value of the option to the current Id in the iteration.

@foreach (var item in selection)
{
     if (item.Id.ToString() == contentId)
     {
         //dont mind this, just for displaying purposes         
     }
     else
     {
        <option value="@item.Id" @(Request.Form["førstePrio"] != null && Request.Form["førstePrio"].ToString().Equals(item.Name.ToString()) ? " selected" : "")>@item.Name</option>
     }
 }

How can I store the @item.Name value as well in a separate Request.Form?

I have two controllers Home and BookReservation , i am trying to redirect from BookReservation controller to view of Home controller without redirect to index of home controller if possible .

this is my action on BookReservation controller :

Validate_rules function return List<string[]> and store them in tempdata

 [HttpPost]
    public ActionResult Validate_Data(ReservationDetails reservation_details)
    {
        TempData["verification_errors"] = Validate_rules(reservation_details);//this function return List<string[]>  

        return RedirectToAction("Index");
    }

and here the view index.cshtml of home i get the temp data and display the elements of it:

 @{
                    List<string[]> validate_rules = new List<string[]>();
                    if (TempData["verification_errors"] != null)
                    {
                        validate_rules = (List<string[]>)TempData["verification_errors"];

                    }
                }                   

                @foreach (var item in validate_rules)
                {                        
                    <label >@item[0].ToString() @item[2].ToString()</label>
                }

the problem is i can not display the validate_rules elements inside view label i don't know where the problem from when i redirect the temp-data from BookReservation controller or what ?

this is home controller :

  [HttpGet] 
    [ActionName("Index")]
    [HandleError]
    public ActionResult Index_Get(string submit)
    {
        bool ParamsChanged = mySessionObject.Parameters.LoadQueryParameters(Request);

        if (ParamsChanged)
            return RedirectToAction("Index", mySessionObject.Parameters.GetQueryParameters());

        LoadHotelDetails();           
        GetHotelAvailability();

        ViewBag.data = TempData["verification_errors"];

        return View("Index",myViewModel);
    }

any advice ?

Using Html Helper with class but it didn't work for my code.

@using (Html.BeginForm())
            {
                <p class="form-title">YOUR NAME <span>(required)</span></p>
                @Html.TextBoxFor(model => model.Name, new { @class = "normal-box"})
                <p class="form-title">YOUR EMAIL <span>(required)</span></p>
                @Html.TextBoxFor(model => model.Email, new { @class = "normal-box" })
                <p class="form-title">SUBJECT</p>
                @Html.TextBoxFor(model => model.Subject, new { @class = "normal-box" })
                <p class="form-title">YOUR MESSEGE</p>
                @Html.TextAreaFor(model => model.Messege, new { @class = "messege-box" })

                <input type="submit" value="SUBMIT"/>
            }

I'm using an ASP.NET MVC web application to make Back-Ups of my VSTS Server.

My DB has a bunch of nested tables, in this case, I am accessing a table called "Project". One of its fields is an ICollectible with Backup being yet another table in my DB / model in my MVC. The projects load just fine in the View that is created with one of the standard Controller templates, the field ICollectible, however, is always null, even though there are definitely "Backups" in my DB.

This is my code:

@model IEnumerable<Backup_Tool.Models.Site>

@functions{
    public string GetLatest(Backup_Tool.Models.Project projekt)
    {
        if (projekt.Backup == null)
            return "( - )";
        DateTime time = DateTime.Now.AddYears(-500);
        foreach (var back in projekt.Backup)
        {
            if (back.CreationTime > time)
                time = back.CreationTime;
        }
        return $"{time.ToShortDateString()}";
    } }
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Uri)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.CreationTime)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Password)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.User)
        </td>
        <td>
            @foreach (var project in item.Projects)
            {
                <p>@Html.DisplayFor(m => project.Name)</p>
                <i>@GetLatest(project)</i>




            }
        </td>

Do I need to add the Backup Model at the top as well? Actually load the Backup, using a DB Context?

This question already has an answer here:

I'm using EF from few days, now I have problem to send (in one view) model with ICollection. The other way it's easy (from controller to view).

Here is an example.

There are classes (sorry for coding in my native language).

First:

public partial class Kontrahenci
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Kontrahenci()
    {
        this.PracownikKontrahenta = new HashSet<PracownikKontrahenta>();
    }

    public int KontrahentId { get; set; }
    public string Nazwa { get; set; }
    public string NazwaSkrocona { get; set; }

    BLA BLA A LOT OF VARIABLES

    public string Gwarancja { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<PracownikKontrahenta> PracownikKontrahenta { get; set; }
}

Second:

public partial class PracownikKontrahenta
{
    public int PracownikId { get; set; }
    public string Imie { get; set; }
    public string Nazwisko { get; set; }
    public string Telefon { get; set; }
    public int IdKontrahenta { get; set; }

    public virtual Kontrahenci Kontrahenci { get; set; }
}

IdKontrahenta is Forgein Key (NOT NULL).

So I want to make a Form where I can send to Controller model with Kontrahent class and ICollection with PracowanikKontrahenta (I will do a js script to append new and new inputs by clicking in button "add next", but first I must know how to send it).

I tried this:

<div class="row">                       
    @Html.TextBoxFor(model => model.PracownikKontrahenta.ToList()[0].Imie)
    @Html.TextBoxFor(model => model.PracownikKontrahenta.ToList()[0].Nazwisko)
    @Html.TextBoxFor(model => model.PracownikKontrahenta.ToList()[0].Telefon)
</div>

But it won't sending to Controller ICollection<PracownikKontrahenta>.

At last PracownikKontrahenta will get foreign key from new model Kontrahenci, and save in db. I will also save Kontrahenci in db ofc.

I would like to move an ASP.NET 2.0.50727 web application from a Windows 2003 onto a Windows 2012 server. * I have set up .NET 3.5 on Windows 2012 server. * I use .NET CLR Version v2.0.50727 and Classic managed pipeline for its application pool * The app uses Windows authenticátion

The application is starting in browsers but the windows authentication is not working. How could I configure it, please?

In my ASP.Net MVC appication I have a loop which i'd like to display different Properties values in HTML using the HTML.DisplayFor method. But it will not accept a string value to direct to the Model parameter.

Normal mode:

<img src="@Html.DisplayFor(model => model.Image_1)" />

My loop:

@for (int i = 1; i < 11; i++)
    {
        string currentImage = "Model.Image_" + i;
        if ((@Html.DisplayFor(model => "Model.Image_" + i ).ToString()) != "")
        {
            <div>
                <img src="@Html.DisplayFor(model => currentImage)" />
            </div>
        }

    }

My results in the img src are just currentImage. I'd like it to be Model.Image_" + i. How would I do that?

If you have a better way of doing this that would be appreciated as well. Should my images have their own Model -class, you think?

I am getting json in below mentioned format.

[{
    "count":"2",
    "data":[{
        "Name": "Pinky",
        "number": "91XXXX",
        "place": "Mumbai"
    },
    {
        "Name": "Rohan",
        "number": "91XXXX",
        "place": "Pune"
    }]
}]

For practice,I have taken it into string like this

string json = "[{
    \"count\":\"2\",
    \"data\":[{
        \"Name\": \"Pinky\",
        \"number\": \"91XXXX\",
        \"place\": \"Mumbai\"
    },
    {
        \"Name\": \"Rohan\",
        \"number\": \"91XXXX\",
        \"place\": \"Pune\"
    }]
}]";

I have created a classes for that .

public class Datum
{
    public string Name { get; set; }
    public string number { get; set; }
    public string place { get; set; }
}

public class RootObject
{
    public string count { get; set; }
    public List<Datum> data { get; set; }
}

But when I am writing like this ,getting error.

RootObject cdr = JsonConvert.DeserializeObject<RootObject>(json); 

I am able to successfully create a .zip file using AddDirectoryByName and AddFile , my code below :-

using (ZipFile zip = new ZipFile())
    {
        zip.AlternateEncodingUsage = ZipOption.AsNecessary;

         zip.AddDirectoryByName("A");

             zip.AddFile("~/.png", "A");
    }

but what happens is that, it creates a folder by name A and inside it, it adds a file (eg. .png).

But I want to place this folder A inside another created folder called "Root", so now how can I create a folder called Root to my .zip and add folder A to that Root ??

Any help thankfully appreciated.

I have question about EF performance.

There are 2 scenarios with using EF (that I use).

  1. I use "using" statement in almost every small part of code.
  2. I create dbcontext on page init and then dispose it on page disposal.

In scenario 1 it happens that I use many times "using" statement for 1 page request. Is this effect performance over using 1 dbcontext for whole page lifecycle.

I ask this as almost all templates, suggestions, examples ... are going with "using" statement, but I kind of think that for asp.net web forms 1 instance of dbcontext is better.

Thanx.

I'm a novice programmer in vb.net and I don't understand how can I get the user Id knowing only the username (or email) in order to let the user reset his password. Is there someone who can teach me how can I solve this? Thanks in advance! Here's my code, adapted from the Microsoft model.

Imports System
Imports System.Linq
Imports System.Web
Imports Microsoft.AspNet.Identity
Imports Microsoft.AspNet.Identity.EntityFramework
Imports Microsoft.AspNet.Identity.Owin
Imports Owin
Imports System.Security.Principal

Protected Sub Reset_Click(sender As Object, e As EventArgs)
Dim manager = Context.GetOwinContext().GetUserManager(Of ApplicationUserManager)()
        'probably wrong
        Dim userId As String = User.Identity.GetUserId()
        'runtime error here, id not found.
        Dim resetToken As String = manager.GeneratePasswordResetToken(userId)

        If resetToken IsNot Nothing Then

            Dim newPassword As String = Password.Text

            Dim user = manager.FindById(userId)
            If user Is Nothing Then
                ErrorMessage.Text = "No user found"
                Return
            End If

            Dim result = manager.ResetPassword(userId, resetToken, Password.Text)
            If result.Succeeded Then
                Response.Redirect("~/Account/ResetPasswordConfirmation")
                Return
            End If
            ErrorMessage.Text = result.Errors.FirstOrDefault()
            Return
        End If

        ErrorMessage.Text = "An error has occurred"

    End Sub

I have two repeaters nested in my application which is working fine. I would love to display the footer if the child repeater is empty. Due to my code my long html, i will just drop a sample of what my html looks like and post my full code for better understanding. Everything works fine though unless when the child repeater is empty i want to display the footer message

<asp:Repeater ID="ProductRepeater" runat="server" OnItemDataBound="ProductRepeater_ItemDataBound">
        <HeaderTemplate></HeaderTemplate>
        <ItemTemplate>
           <table>
<tr>
<td>
<%#Eval("Name")%>
</td>
<tr>
</table>
<pre> <asp:Repeater ID="ChildRepeater" runat="server">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<table>
<tr>
<td>
<%#Eval("Description")%>
<td>
</tr>
<table>
</itemTemplate>
<FooterTemplate>
                                        <div>
                                            <h5><asp:Label ID="lblDefaultMessage" runat="server" Text="This is empty. " Visible="false" ForeColor="Red" Font-Size="Large">
                                                  </asp:Label>
                                                </h5>
                                                </div>

                                        </FooterTemplate>
</asp:Repeater></pre>
          </ItemTemplate>

           </asp:Repeater>


<protected void ProductRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                string category = "Value"
                Repeater rptRelated = e.Item.FindControl("ChildRepeater") as Repeater;
                rptRelated.DataSource = getChild(category);
                rptRelated.DataBind();
                if (rptRelated.Items.Count < 1)
                {
                    if (e.Item.ItemType == ListItemType.Footer)
                    {
                        Label lblDefaultMessage = (Label)e.Item.FindControl("lblDefaultMessage");
                        lblDefaultMessage.Visible = true;

                    } 
                }

            }
        }

Within my code I have an asp repeater and I wish to allow users to export the data from this to a csv file. Exporting to a csv works fine but when I wish to show a dialog box for users to choose where to save to nothing happens. I have went through several different solutions that apparently work but when I run them in my code nothing happens and I can not figure out why. This is my code at the moment:

protected void exportCSV_Click(object sender, EventArgs e)
{
    try
    {
        string FilePath = Server.MapPath("~") + "\\test.csv";
        StringBuilder columnbind = new StringBuilder();
        foreach (Control item in rpt_bookings.Items)
        {
            Literal row1 = (Literal)item.FindControl("ltl_bookingemail");
            Literal row2 = (Literal)item.FindControl("ltl_bookingphone");
            Literal row3 = (Literal)item.FindControl("ltl_bookingcost");
            string fullRow = row1.Text.ToString() + "," + row2.Text.ToString() + "," + row3.Text.ToString();
            columnbind.Append(fullRow);
            columnbind.Append("\r\n");
        }
        //// Creates the file on server
        File.WriteAllText(FilePath, columnbind.ToString());
        string FileName = "test.csv";
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.ClearContent();
        response.Clear();
        response.ContentType = "text/csv";
        response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
        response.TransmitFile(FilePath);
        response.Flush();
        response.End();

        //// Deletes the file on server
        File.Delete(FilePath);

        //response.End();
        lblmsg.Text = "";
    }
    catch (Exception ex)
    {
        Console.Write(ex);
        Debug.Write(ex);
        lblmsg.Text = ex.Message;
        lblmsg.Style.Add("color", "#c73939");
    }
}

The csv is correctly created but nothing happens with the response. The code executes but nothing comes up on the screen at all. According to several other questions along the same lines this is the solution.

Please could you help me with problem on intranet website?

We have problem with website loading because of View State which is very important for keeping data in table. When I disable View State and choose one of the option. This table disappear.

table

Is there any option how to increase loading speed?

Thank you for advises.

I have created FormData object from a form using jquery as bellow. and sending it to the controller side to FormCollection using ajax.

var form = $('#kycFormTab1').get(0);
var data = new FormData(form);

I want to send multiple form data to the ajax. How can i achieve it? How to append form data of the other form to 'data' object?

I want to access form data with name because i am using FormCollection object to the server side.

I haven an event, if I push the Stop button, the Visual Studio sends a word to Arduino. But the Arduino back send to the c#, and with this I want to stop my cycle. With this I want to skip the Ajax but I want to simulate that the data go in live. But my webpage doesn't appear. Has anyone an idea how can I correct it? My code:

 [HttpGet]
        public JsonResult stopButtonOnClick()
        {

            String forthearduino = "1";
            myport.Open();
            myport.Write(forthearduino);
            myport.Close();
            return Json("Ok", JsonRequestBehavior.AllowGet);
        }

In index controller:

 data_rx = myport.ReadLine();
                while(data_rx!="1")
                    {
                   data_rx = myport.ReadLine();
...


                    }

And in the Arduino:

int val = Serial.read();
   if(Serial.available()){
  if (val==1)
  {
    Serial.println("Stop");
  }}