I have a .NET MVC project and I'm trying to download a file from temporary folder. Here is my view code:

window.open('@Url.Action("DownloadDocument", "Controller")?fileName=' + fileName, '_blank');

And here is my controller code:

    public FileResult DownloadDocument(string fileName)
    {
        string path = Web.Common.Properties.Settings.Default.TempDocPath + "OpenTable\\";
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }

        return File(fileName, "application/xml", fileName + ".xml");
    }

This code works on IIS and file is being downloaded. But I'm getting 500 error when trying to download it from remote server.

This site can’t be reached The webpage at <...> might be temporarily down or it may have moved permanently to a new web address. ERR_INVALID_RESPONSE

And the worst part is that there are some almost exact code snippets in the system which are working in both IIS and remote server.

Any suggestions what could be done?

I am testing this on chrome. I have set chrome to remember user name and passwords. I have a very simple MVC 5 web application where i have login screen and also screen to create user. When user log in, I let chrome save user name and password.

Problem is that when I try to create new user, its not coming user name as blank, but still showing user name that I logged in with.

I want to do in view and not through controller default vault. I tried using below example link on SO, but my code is still not working

how to set default value HTML.EditorFor()

Here is the code that I tried and its not working.

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

Please advice what should I do to fix this. You you.

I am trying to create a textbox for a dollar amount such as 5.00 or 500.00 and the way I would like it to work is if the user types in 5, the value in the textbox will display 0.05 and if the user types in 500 the value in the textbox will display 5.00. I currently have a mask on the textbox to allow 999999.99 input along with a placeholder of zeros for display as 000000.00. I also have css direction set to rtl, but it doesn't work the way it should. The user is still inputting normal direction, everything is just now right aligned which isn't what I was going for.

I tried searching for some solutions, but have had zero luck. Is there anything available to achieve this type of input? Most of what I found is for displaying of certain languages such as Hebrew and I'm just looking for something to handle the input of a decimal fixed value.

Here is my javascript

@section scripts{
<script src="~/Scripts/jquery.maskedinput.js" type="text/javascript"></script>
<script type="text/javascript">
    $('form :input:visible:enabled:first').focus();
    $('#check_checkAmount').mask('999999.99', { placeholder: "000000.00" });
    $('#check_checkAmount').css('direction', 'rtl');
</script>
}

And here is my html of the control

@Html.TextBoxFor(model => model.check.checkAmount, new { @class = "form-control" })

As of right now the way it works with the code you see above if the user enters 5 it will display 500000.00 and not 000000.05 like I want. Adding the css direction = rtl it did change the textbox alignment to right. I don't necessarily need the textbox to align to right, I just need to be able to input the value from the right to the left.

I also tried the same code above with the placeholder being "" and that doesn't work either. It wouldn't make a ton of sense if it made a difference, but it was worth a shot. lol.

Thank you so much for any help.

By Web Notification I mean this (The Notification interface of the Notifications API is used to configure and display desktop notifications to the user).
I have Asp.Net MVC web app and I have a button in my page which supposed to push a notification to clients.
I also used signalr to push message and call notification function.

my layout.cshtml looks like this:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
</head>
<body>
    <button id="btn" type="button">click</button>
    @RenderBody()
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.signalR-2.2.1.min.js"></script>
    <script src="~/signalr/hubs"></script>
    <script>
        jQuery(function ($) {
            var myHub = $.connection.chatHub;
            myHub.client.addNewMessageToPage = function (title, message) {
                var options = {
                    body: message,
                    tag: 'aaa'
                }

                // check permissions if already granted
                if (Notification.permission === "granted") {
                    var notification = new Notification(title, options);
                } else if (Notification.permission !== 'denied') {
                    // request permission
                    Notification.requestPermission(function (permission) {
                        // If the user accepts, let's create a notification
                        if (permission === "granted") {
                            var notification = new Notification(title, options);
                        }
                    });
                }

                console.log('the hub method called sucessfully');
            }
            $.connection.hub.logging = true;
            $.connection.hub.start().done(function () {
                $('#btn').on('click', function () {
                    myHub.server.send('foo', 'bar');
                });
            });
        });
    </script>
</body>
</html>

The problem is, the push notifications stops working/showing in firefox when I have multiple pages of my app open. (it works when single tab is open).
this bug only happens in firefox and works well in chrome and IE.

animated gif

update 1: I think its not signalr problem since the hub method is invoked.
this line is called on all tabs: console.log('the hub method called sucessfully');
and signalr logging says that:

SignalR: Invoking myhub.Send jquery.signalR-2.2.1.min.js
SignalR: Triggering client hub event 'addNewMessageToPage' on hub 'MyHub'. jquery.signalR-2.2.1.min.js
foo bar
SignalR: Invoked myhub.Send jquery.signalR-2.2.1.min.js

I am migrating an ASP.NET application to ASP.NET Core and they have some calls to HttpServerUtility.Transfer(string path). However, HttpServerUtility does not exist in ASP.NET Core.

Is there an alternative that I can use? Or is Response.Redirect the only option I have?

I want to maintain the same behaviour as the old application as much as possible since there is a difference in between Server.Transfer and Response.Redirect.

I have the following dataset:

<asp:SqlDataSource ID="staffcategories" runat="server" ConnectionString="<%$ ConnectionStrings:PalestineNewsConnectionString %>" SelectCommand="SELECT * FROM [CategoriesStaff]"></asp:SqlDataSource>
            <asp:DataList ID="DataList1" runat="server" DataSourceID="staffcategories" RepeatDirection="Horizontal" HorizontalAlign="Center" RepeatLayout="Flow" ShowFooter="False" ShowHeader="False">
                <ItemTemplate>
                    <div class="fl_left">
                        <a href="<%# Eval("Cat_Name_en")%>.aspx">
                        <img src="data:image/jpeg;base64,<%# Eval("Picture") %>" alt="" /></a><br />
                        <p><%# Eval("Cat_Name_en")%></p>
                        <p><%# Eval("Description")%></p>
                    </div>
                </ItemTemplate>
            </asp:DataList>

Is it possible in every 2 loops to add a <br />?

I have a gridview with two columns and I wand to add a third column which will be column a divided by column b. I added a template field but I am getting a divide by zero error. I can I check for zero values to stop the error message?

<asp:TemplateField>
 <ItemTemplate>
  <asp:Label ID="lblCalc" runat="server" ><%# Convert.ToDecimal(Eval("val1").ToString()) / Convert.ToDecimal(Eval("val2").ToString()) %></asp:Label>
  </ItemTemplate>
</asp:TemplateField>

I have a table in which i have data like this

enter image description here

I want to use this data to make views Create,Index,Edit Is this possible in asp.net MVC??

Like On Conditionally i will check if Recon_type_id == 1 then render view using this data and so on..

I want to Do it like this:

like in my Index action

 Public ActionResult Index()
    {

        var L2EQuery = context.Students.where(s => s.Recon_Type_ID== 1).Select(s=>s.DB_FIELDS).tolist();
         //Then here create model using names of this list and return this to  view

      return(modelCreatedByListofNames);
    }

Let's say I have a static class with the following extension method which retrieves the file from the Cache or reads it from disk and puts it in the Cache if it is not there + makes some changes to the content (e.g., add tags or attributes):

public static class Foo
{
  public static DoSomething(this HtmlHelper helper, string url, List<string> parameters)
  {
     string content = String.Empty;
     var cache = HttpContext.Current.Cache[url];

     if (cache == null)
     {
       string absolute_path = WebPages.HelperPage.Server.MapPath(url);
       content = File.ReadAllText(absolute_path);
       HttpContext.Current.Cache.Add(url, content, ...);
     }
     else
     {
       content = cache.ToString();
     }

     //make a few changes to content (e.g., add some tags or attributes)
     content = makeChangesToContent(content, parameters);

     return MvcHtmlString.Create(content);
  }
}

This method is used in the razor view like this:

   @Html.DoSomething("/path/to/file", new List<string>(){"param1", "param2"});

To make this code testable I have to remove all the dependencies from the method. But since it is static and used in the razor view I'm not sure how to do it right.

The only one option came to my mind is to use Shims to fake external dependencies with some fake methods. But the unit test code looks a bit heavy and it takes around 200ms to run it.

Here is a quick example of the unit test:

[Test]
public void DoSomething_Should_Return_FileContent_From_Cache_When_It_Is_There()
{
    string relativeFilePath = "/some/path";
    string fileContent = "content";
    string cachedKey = String.Empty;
    object cachedValue = null;

    using (ShimsContext.Create())
    {
        //Arrange
        System.Web.Fakes.ShimHttpContext.CurrentGet = () =>
        {
            var httpContext = new System.Web.Fakes.ShimHttpContext();

            httpContext.CacheGet = () =>
            {
                var cache = new System.Web.Caching.Fakes.ShimCache();

                cache.ItemGetString = (key) =>
                {
                    cachedKey = key;
                    cachedValue = fileContent;

                    return fileContent;
                };

                return cache;
            };

            return httpContext;
        };

        //Act
        var result = helper.DoSomething(relativeFilePath, new List<string>(){"param1", "param2"});

        //Assert
        Assert.IsTrue(cachedKey.Equals(relativeFilePath));
        Assert.IsTrue(cachedValue.Equals(fileContent));
    }

Is it correct way to test it? Are there any better options? From you experience, what is the best approach to test such static methods?

I am trying to populate a listbox and parse the selected option back to the controller. Problem is I can't seem to figure out BeginForm and Listboxfor. The tutorials found online only confuse me more.

Here's my csHtml:

@Html.BeginForm("BtnSelectPost", "TimelinePageController")
    {
        <div>
             <select id="s1" class="timeline" size="20" name="Options">
                    @foreach (var C in Model)
                    {
                        Html.ListBoxFor(?)
                    }
             </select>
        </div>
    }

Here's my Controller:

        public List<Contribution> Contriblist = new List<Contribution>();
    // GET: TimelinePage
    public ActionResult TimelinePage(Event Event)
    {        
        Contriblist = DatabaseGetContribution.GetContributions(Event.ID);
        return View(Contriblist);
    }

        public SelectList GetAllContrib()
    {
        SelectList Contribslist = new SelectList(Contriblist, "ID", "Text");
        return Contribslist;
    }

What would I have to do to get it working?

Any help would be great

EDIT: I'm sorry for the lack of information: I'm using 2 models. Contribution:

    public int ID { get; set; }
    public int ContributionID { get; set; }
    public DateTime DateTime { get; set; }    
    public string Category { get; set; }
    public int Likes { get; set; }
    public int Reports { get; set; }    
    public int PostID { get; set; }
    public byte[] File { get; set; }
    public string Attachment { get; set; }
    public Message Message { get; set; }

    /// <summary>
    /// Create Constructor
    /// </summary> 
    /// <param name="category">The category of a post</param>    
    /// <param name="likes">The amount of likes of a post</param> 
    /// <param name="file">The file belonging to the post</param>
    /// <param name="postID">This is the ID of the post reacted to</param>
    public Contribution(DateTime datetime, string category, int likes, int reports, int postid, Message message)
    {           
        this.Category = category;    
        this.Likes = likes;
        this.Reports = reports;
        this.PostID = postid;
        this.DateTime = datetime;
        this.Message = message;
    }

And ViewModelContrib:

public IEnumerable<SelectListItem> contrib { get; set; }

The values in contribution are taken from a database and the Event is only used to take the ID from to check which contributions should be taken from the database.

Thank you all for your help.

In my web api I' m using Unity IOC as my dependancy resolver. It is working very nicely in my Visual Studio debugger and azure web service. But when I deployed that to VM or local IIS it's not resolving. I attached a debugger to VM w3wp process it register the type nicely but it get's an error like this. I don't know whether it's an issue with DLLs

Internal server error : An error occurred when trying to create a controller of type '__Controller'. Make sure that the controller has a parameterless public constructor. | at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request) at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()

Any one has experienced with this issue

It's maybe a "dumb" question.

I want to start with asp.net with combination of classic asp.

Now do I have a large header (codeUp.asp) (500 line) (in this header i have the menu, layout etc, etc) and a footer (codeDown.asp). I want to use this in my aspx. Is this possible. ( tried renderpage )(I can't use html raw (because I have some asp codes that must be running))

I use razor syntax !

The reason I ask here is because I am new to asp.net.

Telerik : UI for ASP.NET MVC

Version : 2016.3.1118.545

Hi folks,

I’m facing some difficulty with the export PDF. I’m using the great kendo Grid to get the minimal data from server using the pager.

When I ask for excel export, multi requests are executed to get all the data from the server in order to produce the excel file (client ide) => Works pretty well

When I ask for PDF export, multi request are executed to get all the data from the server in order to produce the PDF file (client side) => got an issue, see below.

Actually, if I comment the PaperSize option or use the paperSize(“auto”) I got all the pages but the TemplateId is not used. If I used the option paperSize(“A4”) the templateId (Header, footer) are displayed but only the data from the current pager are include to the pdf file.

Thx in advance for your help,

Any idea about it.

Below a piece of my code.

 @(Html.Kendo().Grid<Connexity.MvcUI.Converters.ToJson.AlertConverter.AlertInfoUIDto>()
        .HtmlAttributes(new { @data_scroll = "auto" })
        .Name("AlertHistoricGrid")
        .Events(e => e.DataBound("alertLib.gridDataBound"))
        .ToolBar(tools => tools.Excel().Text(Resources.Generic_Export + " " + Resources.Generic_Excel))
            .Excel(excel => excel
            .FileName(Resources.AlertHistoric_List_Title + ".xlsx")
            .AllPages(true)
            .Filterable(true)
            .ProxyURL(Url.Action("Telerik_Export_Save", "Helper"))
        )
        .ToolBar(tools => tools.Pdf().Text(Resources.Generic_Export + " " + Resources.Generic_ToPDF))
            .Pdf(pdf => pdf
            .AvoidLinks()
            //.PaperSize("A4") // uncomment this line to got only the data from current pager into the pdf export file
            .Scale(0.8)
            .Margin("2cm", "1cm", "1cm", "1cm")
            .Landscape()
            .RepeatHeaders()
            .TemplateId("PDFTemplate")
            .FileName(Resources.AlertHistoric_List_Title + ".pdf")
            .AllPages()
            .ProxyURL(Url.Action("Pdf_Export", "Alert"))
        )
        .DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(15)
        .Read(read => read.Action("AlertInfo_Read", "Alert").Data("alertLib.getAdditionalData").Type(HttpVerbs.Post)
        )
        )
        .Columns(columns =>
        {
        columns.Template(@<span></span>).Width(10).ClientTemplate("#=library.getKendoTemplate(data,'SelectionTemplate')#")
        .HeaderTemplate(
            @<span class="grid-selection">
                <input name="cbSelectionAll" class="select-all" id="CBAlertAll" type="checkbox" />
                <label class="kgrid-selection" for="CBAlertAll"></label>
            </span>)
        .HeaderHtmlAttributes(new { Class = "header-checkbox-column" })
        .Title("")
        .Visible(canCloseMultipleAlerts)
        .HtmlAttributes(new { Class = "checkbox-column" });
        columns.Bound(p => p.StateName).Width(62).ClientTemplate("#=library.getKendoTemplate(State,'StateTemplate')#").Title(Resources.Generic_State);
        columns.Bound(p => p.AlertStartDateTime).ClientTemplate("#=library.getKendoTemplate(data,'StartDateTimeTemplate')#").Title(Resources.AlertHistoric_AlertStart);
        columns.Bound(p => p.AlertTypeName).Title(Resources.Generic_AlertType);
        columns.Bound(p => p.DeviceName).Title(Resources.Generic_Name);
        columns.Bound(p => p.DeviceIdentifiant).Title(Resources.Generic_Identifiant);
        columns.Bound(p => p.SensorNames).ClientTemplate("#=library.getKendoTemplate(Sensors,'SensorTemplate')#").Title(Resources.Generic_Sensor);
        columns.Bound(p => p.AlertEndDateTime).ClientTemplate("#=library.getKendoTemplate(data,'EndDateTimeTemplate')#").Title(Resources.AlertHistoric_AlertResolution);
        columns.Template(@<span></span>).ClientTemplate("#=library.getKendoTemplate(data,'ActionTemplate')#").Title(Resources.AlertHistoric_Actions);
        columns.Template(@<span>@item.SMSCount @item.EmailCount</span>).ClientTemplate("#=library.getKendoTemplate(data,'NotificationTemplate')#")
        .Title(Resources.AlertDetailsModal_AlertHistoricNotifications).Width(220);
        columns.Template(@<span></span>).Title("").Width(42).ClientTemplate(Html.ActionLink(" ", "DetailsModal", "Alert", new { idAlert = "#=IdAlert#" }, new { data_toggle = "modal", data_target = "\\#basicModal", data_modal = "", Class = "button detail" }).ToHtmlString())
            .HeaderHtmlAttributes(new { Class = "header-button-column" }).HtmlAttributes(new { Class = "button-column" });
        })
        .Sortable()
        .Pageable()
    )

To All Can Any body suggested me Any library for Face detection in ASP.NET Web?? Actually In our Final Year project we want Facial Recognition Process : There was Some Test and when Test start we ask permission of the User IF user Allow Test continues otherwise we Stop test and then take silent images to verify is right person is giving test or Not . Please Remember We want in asp.net web

Best Regards Ahmad Shabbir

I'm an ambitious millennial who has chosen to self-teach myself a few things that could obtain me success. One of them is software development - with two possible avenues for success - create my own website, and be my own boss. The other is - to get certified through Microsoft in my area of expertise and work for a company. My area of expertise? Well, I'll try to be quick here, I started learning ASP a long time ago, and then I learned ASP.NET WebForms, and then, most recently, I've learned and have gotten a pretty good grasp of ASP.NET MVC. So, my issue is this:

I've had my eye on doing this for a while now, and I noticed how Microsoft modifies its Exam's every year, so, every so often, I check on the MCSD testing page to see what's currently offered. At the time of this writing, what I'm interested in is becoming what's now, in December 2016, known as a Microsoft Certified Solutions Developer for Web Applications (the MCSD: Web Applications certification branch), but I just found out the certification expires on March, 31 2017.

The exact page that made me feel alarmed on the topic is - https://www.microsoft.com/en-ca/learning/mcsd-web-apps-certification.aspx - and, the exact quote was "Note This certification will retire on March 31, 2017. When the certification retires, all individuals whose transcripts list this certification as active on or after September 26, 2016, will retain the active status. Find out about the replacement certification, MCSD: App Builder."

As I said, I'm ambitious, and have a few avenues I can pursue. Although, as I said, I've been interested in getting this certification for some time now, but, it's just that I've been busy doing many things, and I'm unsure if I can complete the exam by that date, and the new replacement certification branch (MCSD: App Builder) doesn't make sense to me, I want to develop with C# and MVC, and I don't want to have anything to do with Azure - which is what that new replacement branch is focused on - while the current branch that's available till March, 31 2017 - has a specific exam for MVC developers (Developing ASP.NET MVC Web Applications). I don't understand why Microsoft feels this change is necessary, this is alienating developers like myself. I don't know what to do, I wish there was something I am unaware of here, and there still will be some kind of exam offered specifically for MVC (I mean, since MVC was introduced, there's been an exam specifically for it - and now, they want to get rid of the focus on it altogether when it comes to certification? Maybe it's because Microsoft just made ASP.NET and MVC (under the new "Core" Framework) to be open source...)

If anybody here has any reassuring information for me, or some kind of information that'd help in some way pertaining to this, I would really appreciate it.

how to debug this error.can u please help me..

error: No mapping exists from object type System.Web.UI.WebControls.FileUpload to a known managed provider native type.

program:

enter code here

public partial class HrInfo : System.Web.UI.Page {

protected void Page_Load(object sender, EventArgs e)
{


}
protected void btn_insrt_Click(object sender, EventArgs e)
{
    try
    {
        SqlConnection con = new SqlConnection("Data Source=SYSTEM-6-PC;Initial Catalog=HRMS;Integrated Security=True");
        con.Open();

        FileUpload img = (FileUpload)imgUpload;
        Byte[] imgByte = null;
        if (img.HasFile && img.PostedFile != null)
        {
            //To create a PostedFile
            HttpPostedFile File = imgUpload.PostedFile;
            //Create byte Array with file len
            imgByte = new Byte[File.ContentLength];
            //force the control to load data in array
            File.InputStream.Read(imgByte, 0, File.ContentLength);
        }
        SqlCommand cmd = new SqlCommand("INSERT INTO HR_information([HRName],[HRCode],[Designation],[Department],[Qulification],[DateOfBirth]"
      + ",[Phone],[Mobile],[MaritalStatus] ,[Email] ,[ZipCode],[Address] ,[Street],[City] ,[State] ,[Country],[Photo],[PassportNo]) VALUES (@HRName,@HRCode,@Designation,@Department,@Qulification,@DateOfBirth"
      + ", @Phone,@Mobile,@MaritalStatus,@Email @ZipCode,@Address,@Street,@City,@State,@Country,,@eimg,@ PassportNo)", con);

        cmd.Parameters.AddWithValue("@HRName", txt_name.Text);
        cmd.Parameters.AddWithValue("@HRCode", txt_code.Text);
        cmd.Parameters.AddWithValue("@Designation", drpdwn_desig.SelectedItem.ToString());
        cmd.Parameters.AddWithValue("@Department", drpdwn_dept.SelectedItem.ToString());
        cmd.Parameters.AddWithValue("@Qulification", txt_qual.Text);
        cmd.Parameters.AddWithValue("@DateOfBirth", txt_dob.Text);
        cmd.Parameters.AddWithValue(" @Phone", txt_phn.Text);
        cmd.Parameters.AddWithValue("@Mobile", txt_mob.Text);
        cmd.Parameters.AddWithValue("@MaritalStatus", Dropdownmatrialstatus.SelectedItem.ToString());
        cmd.Parameters.AddWithValue("@Email", txt_email.Text);
        cmd.Parameters.AddWithValue("@ZipCode", txt_zip.Text);
        cmd.Parameters.AddWithValue("@Address", txt_addr.Text);
        cmd.Parameters.AddWithValue("@Street", txt_str.Text);
        cmd.Parameters.AddWithValue("@City", txt_cty.Text);
        cmd.Parameters.AddWithValue("@State", drpdwn_state.SelectedItem.ToString());
        cmd.Parameters.AddWithValue("@Country", txt_ctry.Text);
        cmd.Parameters.AddWithValue(",@eimg", img);
        cmd.Parameters.AddWithValue("@ PassportNo", txt_passportno.Text);

        cmd.ExecuteNonQuery();






    }
    catch (Exception)
    {
    }


}

}

I am currently having an ASP.NET Core application that is attached to an IIS/ Azure App Service using the following web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.webServer>
        <handlers>
            <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
        </handlers>
        <aspNetCore processPath=".\MyDotNetCoreApp.exe" arguments="" stdoutLogEnabled="false" stdoutLogFile=".\stdout.txt" forwardWindowsAuthToken="false" />
    </system.webServer>
</configuration>

The application has been built with "Microsoft.AspNetCore.Server.Kestrel" and "Microsoft.AspNetCore.Server.IISIntegration" added as dependencies and uses the following bootstrapping code:

IWebHost Host = new WebHostBuilder()
  .UseKestrel()
  .UseIISIntegration()
  .UseStartup<WebSocketServerConduit>()
  .Build();

Everything works magnificently; however, once the App Service is shutdown, the app is simply terminated.
Is there any way to catch the "shutdown signal" of the IIS/ App Service and thus perform cleanup tasks?

Help is greatly appreciated.
Thanks in advance and best regards
-Simon

I have a Details View that contains a drop down list. I have the drop down list being populated and I have the drop down list item that matches the database entry as the default selection. The problem I'm having is when I try to update, the database entry becomes null.

I have tried using the Update Command from the datasource with the selected value of the drop down list. I have also tried using cmd.Parameters.AddWithValue("@EncID", ddl.SelectedValue.ToString());

I know using ddl.SelectedIndex = 1; gives me the first selection, but I'm just trying to get this to work with the first entry. I will be modifying it once I can get the database to update properly

This is the c# code:

protected void ddlEncroachmentTypes_DataBound(object sender, EventArgs e)
{
    dbcon = new SqlConnection(ConfigurationManager.ConnectionStrings["LakeEncroManSys"].ConnectionString);
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "SELECT RowNum from(Select ID, Name, RowNum = ROW_NUMBER() over(order by ID) from tblEncroachmentTypes) as temp where temp.Name Like (Select EN_TYPE from LakeEncroachments WHERE EN_ID = @EncID)";
    cmd.Parameters.AddWithValue("@EncID", LastNameGrid.SelectedValue.ToString());
    cmd.CommandType = CommandType.Text;
    cmd.Connection = dbcon;
    dbcon.Open();



    if (dvEncroachment.CurrentMode == DetailsViewMode.Edit && cmd.ExecuteScalar() != null)
    {
        long rowNum = (long)cmd.ExecuteScalar();

        DropDownList ddl = (DropDownList)dvEncroachment.FindControl("ddlEncroachmentTypes");
        ddl.SelectedIndex = (int)rowNum - 1;

    }
    else if(dvEncroachment.CurrentMode == DetailsViewMode.ReadOnly)
    {
        DropDownList ddl = (DropDownList)dvEncroachment.FindControl("ddlEncroachmentTypes");
        ddl.SelectedIndex = 1;

        SqlDataSource1.UpdateParameters["EN_TYPE"].DefaultValue = ddl.SelectedItem.Value.ToString();

    }

    dbcon.Close();
}

This is the aspx code

<asp:DetailsView ID="dvEncroachment" runat="server" Height="50px" Width="100%" DataSourceID="SqlDataSource1" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black" DataKeyNames="OBJECTID" AutoGenerateRows="False">
                <EditRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
                <Fields>
                    <asp:CommandField ShowEditButton="True" ButtonType="Button" ShowInsertButton="True" />
                    <asp:BoundField DataField="EN_ID" HeaderText="Encroachment ID" SortExpression="EN_ID" />
                    <asp:BoundField DataField="DATE_INSP" HeaderText="Date Inpected" SortExpression="DATE_INSP" />
                    <asp:BoundField DataField="PHOTO_ID" HeaderText="Photo UNC" SortExpression="PHOTO_ID" />
                    <asp:TemplateField HeaderText="Encroachment Type" SortExpression="NAME">
                        <EditItemTemplate>
                            <asp:DropDownList ID="ddlEncroachmentTypes" runat="server" DataSourceID="dsEncroachmentTypes" DataTextField="Name" OnDataBound="ddlEncroachmentTypes_DataBound"></asp:DropDownList>
                        </EditItemTemplate>
                        <ItemTemplate>
                                <asp:DropDownList ID="ddlEncroachmentTypes" runat="server" DataSourceID="SqlDataSource1" DataTextField="EN_TYPE" OnDataBound="ddlEncroachmentTypes_DataBound" disabled="disabled"></asp:DropDownList>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="PETROL" HeaderText="Gas" SortExpression="PETROL" />
                    <asp:BoundField DataField="FPC" HeaderText="FPC" SortExpression="FPC" />
                    <asp:BoundField DataField="NUM_SLIPS" HeaderText="Number of Slips" SortExpression="NUM_SLIPS" />
                    <asp:BoundField DataField="COVERED" HeaderText="Covered" SortExpression="COVERED" />
                    <asp:BoundField DataField="WALLS" HeaderText="Walls" SortExpression="WALLS" />
                    <asp:BoundField DataField="COLOR" HeaderText="Color" SortExpression="COLOR" />
                    <asp:BoundField DataField="PRIVATE_BOOMS" HeaderText="Private Booms" SortExpression="PRIVATE_BOOMS" />
                    <asp:BoundField DataField="SWIM_AREA" HeaderText="Swim Area" SortExpression="SWIM_AREA" />
                    <asp:BoundField DataField="BOUYS" HeaderText="Bouys" SortExpression="BOUYS" />
                    <asp:BoundField DataField="EXCESS" HeaderText="Excess" SortExpression="EXCESS" />
                    <asp:BoundField DataField="LIFT" HeaderText="Boat Lift" SortExpression="LIFT" />
                    <asp:BoundField DataField="BOAT_RAMP" HeaderText="Boat Ramp" SortExpression="BOAT_RAMP" />
                    <asp:BoundField DataField="FLOAT_TYPE" HeaderText="Float Type" SortExpression="FLOAT_TYPE" />
                    <asp:BoundField DataField="FLOAT_CON" HeaderText="Float Construction" SortExpression="FLOAT_CON" />
                    <asp:BoundField DataField="PILE_TYPE" HeaderText="Pile Type" SortExpression="PILE_TYPE" />
                    <asp:BoundField DataField="PILE_CON" HeaderText="Ile Construction" SortExpression="PILE_CON" />
                    <asp:BoundField DataField="DECK_TYPE" HeaderText="Deck Type" SortExpression="DECK_TYPE" />
                    <asp:BoundField DataField="DECK_CON" HeaderText="Deck Construction" SortExpression="DECK_CON" />
                    <asp:BoundField DataField="EROSION" HeaderText="Erosion" SortExpression="EROSION" />
                    <asp:BoundField DataField="WATER_WITH" HeaderText="Water With" SortExpression="WATER_WITH" />
                    <asp:BoundField DataField="SEPTIC" HeaderText="Septic" SortExpression="SEPTIC" />
                    <asp:BoundField DataField="DENSITY" HeaderText="Density" SortExpression="DENSITY" />
                    <asp:BoundField DataField="LAUNCH" HeaderText="Launch" SortExpression="LAUNCH" />
                    <asp:BoundField DataField="COM_COVER" HeaderText="Comercial Cover" SortExpression="COM_COVER" />
                    <asp:BoundField DataField="COM_HOOK" HeaderText="Comercial Hookup" SortExpression="COM_HOOK" />
                    <asp:BoundField DataField="COM_BOXES" HeaderText="Comercial Boxes" SortExpression="COM_BOXES" />
                    <asp:BoundField DataField="COM_FUEL" HeaderText="Comercial Fuel" SortExpression="COM_FUEL" />
                    <asp:BoundField DataField="COM_FUEL_W" HeaderText="Comercial Fuel W" SortExpression="COM_FUEL_W" />
                    <asp:BoundField DataField="COM_BREAK" HeaderText="Comercial Break" SortExpression="COM_BREAK" />
                    <asp:BoundField DataField="Com_slips" HeaderText="Comercial Slips" SortExpression="Com_slips" />
                    <asp:BoundField DataField="Com_feet" HeaderText="Comercial Feet" SortExpression="Com_feet" />
                    <asp:BoundField DataField="Com_br_len" HeaderText="Comercial BR LEN" SortExpression="Com_br_len" />
                    <asp:BoundField DataField="HOME_PHONE" HeaderText="Home Phone" SortExpression="HOME_PHONE" />
                    <asp:BoundField DataField="HOME_ELEC" HeaderText="Home Electric" SortExpression="HOME_ELEC" />
                    <asp:BoundField DataField="HOME_WATER" HeaderText="Home Water" SortExpression="HOME_WATER" />
                    <asp:BoundField DataField="HOME_SEP" HeaderText="Home Sceptic" SortExpression="HOME_SEP" />
                    <asp:BoundField DataField="HOME_FUEL" HeaderText="Home Fuel" SortExpression="HOME_FUEL" />
                    <asp:BoundField DataField="GARBAGE" HeaderText="Garbage" SortExpression="GARBAGE" />
                    <asp:BoundField DataField="NOTES" HeaderText="Notes 1" SortExpression="NOTES" />
                    <asp:BoundField DataField="NOTES2" HeaderText="Notes 2" SortExpression="NOTES2" />
                    <asp:BoundField DataField="NOTES3" HeaderText="Notes 3" SortExpression="NOTES3" />
                    <asp:BoundField DataField="ACTION_REC" HeaderText="Action Required" SortExpression="ACTION_REC" />
                    <asp:BoundField DataField="ACTION_WH" HeaderText="Action With Held" SortExpression="ACTION_WH" />
                    <asp:BoundField DataField="X" HeaderText="Longitude" SortExpression="X" />
                    <asp:BoundField DataField="Y" HeaderText="Latitude" SortExpression="Y" />
                    <asp:BoundField DataField="URL" HeaderText="URL" SortExpression="URL" />
                    <asp:BoundField DataField="WIDTH" HeaderText="Width" SortExpression="WIDTH" />
                    <asp:BoundField DataField="SQFOOTAGE" HeaderText="Sq Footage" SortExpression="SQFOOTAGE" />
                    <asp:BoundField DataField="RIPRAPLENGTH" HeaderText="RipRap Length" SortExpression="RIPRAPLENGTH" />
                    <asp:BoundField DataField="LIFTSNUM" HeaderText="Number of Lifts" SortExpression="LIFTSNUM" />
                    <asp:BoundField DataField="SKIDOCKSNUM" HeaderText="Number ofSki Docks" SortExpression="SKIDOCKSNUM" />
                    <asp:BoundField DataField="RECALCITRANT" HeaderText="Recalcitrant" SortExpression="RECALCITRANT" />
                    <asp:BoundField DataField="PRIORNOTICE" HeaderText="Prior Notice" SortExpression="PRIORNOTICE" />
                    <asp:BoundField DataField="PARCELID" HeaderText="Parcel ID" SortExpression="PARCELID" />
                    <asp:BoundField DataField="WATERSHORELINE" HeaderText="Water Shoreline" SortExpression="WATERSHORELINE" />
                    <asp:BoundField DataField="WATERWAY" HeaderText="Waterway" SortExpression="WATERWAY" />
                    <asp:BoundField DataField="STATEISSUEDATE" HeaderText="State Issued Date" SortExpression="STATEISSUEDATE" />
                    <asp:BoundField DataField="COMPANYASSOC" HeaderText="Company Association" SortExpression="COMPANYASSOC" />
                    <asp:BoundField DataField="STRUCTURALCOMMENTS" HeaderText="Structural Comments" SortExpression="STRUCTURALCOMMENTS" />
                    <asp:BoundField DataField="PERMITEE" HeaderText="Permitee ID" SortExpression="PERMITEE" />
                    <asp:BoundField DataField="BILLTOPERSON" HeaderText="Bill to Person ID" SortExpression="BILLTOPERSON" />
                    <asp:BoundField DataField="InvoiceBillTo" HeaderText="Invoice Bill To ID" SortExpression="InvoiceBillTo" />
                    <asp:BoundField DataField="ANNUALREVENUE" HeaderText="Annual Revenue" SortExpression="ANNUALREVENUE" />
                    <asp:BoundField DataField="EXEMPTCODE" HeaderText="Exempt Code" SortExpression="EXEMPTCODE" />
                    <asp:BoundField DataField="NUMBEROFSTRINGS" HeaderText="Number of Strings" SortExpression="NUMBEROFSTRINGS" />
                    <asp:BoundField DataField="TYPE" HeaderText="Encroachment Type" SortExpression="Type" />
                    <asp:BoundField DataField="Physical_Status" HeaderText="Physical Status" SortExpression="Physical_Status" />
                    <asp:BoundField DataField="X_Old" HeaderText="Longitude Old" SortExpression="X_Old" />
                    <asp:BoundField DataField="Y_Old" HeaderText="Latitude Old" SortExpression="Y_Old" />
                    <asp:BoundField DataField="Dist" HeaderText="Distance from Shore" SortExpression="Dist" />
                    <asp:BoundField DataField="Depth" HeaderText="Depth" SortExpression="Depth" />
                    <asp:BoundField DataField="Pile_num" HeaderText="Number of Pilings" SortExpression="Pile_num" />
                    <asp:BoundField DataField="OBJECTID" HeaderText="OBJECTID" InsertVisible="False" ReadOnly="True" SortExpression="OBJECTID" />

                </Fields>
                <FooterStyle BackColor="#CCCCCC" />
                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />                    
            </asp:DetailsView>
            <asp:SqlDataSource ID="dsEncroachmentTypes" runat="server" ConnectionString="<%$ ConnectionStrings:EncroManConnectionString %>" SelectCommand="SELECT [Name] FROM [tblEncroachmentTypes] ORDER BY [ID]"></asp:SqlDataSource>

I have an mvc app using razor files cshtml and I would like to implement paging. There is an example of getting the table data displayed at this link: how to display database data in tables in view in mvc.

I would like to know how I can add paging to the example as provided in the answer ?

I'm trying to have a website export a .xlsm file and I can't seem to find anything that helps. Here's a simple example I'm using to test building a .xlsx file (which works).

@using OfficeOpenXml;
<html>
    <body>
        <div id="page-wrapper">
        @{
            // Change file extension to xlsm to test
            string fileExtension = "xlsm";
            ExcelPackage p = new ExcelPackage();
            p.Workbook.Worksheets.Add("Worksheet Name");
            int LatestWorksheetNumber = p.Workbook.Worksheets.Count;
            ExcelWorksheet ws = p.Workbook.Worksheets[LatestWorksheetNumber];

            ws.Cells[1, 1].Value = "Test";

            //Generate A File
            Byte[] bin = p.GetAsByteArray();
            string filename = "filename";
            try
            {
                //Download the file as an attachment
                Response.Clear();
                Response.ClearContent();
                Response.ClearHeaders();
                Response.Cookies.Clear();

                string ContentType = "";
                if (fileExtension == "xlsx")
                {
                    ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                }
                else
                {
                    ContentType = "application/vnd.ms-excel.sheet.macroEnabled.12";
                }
                Response.GetType();
                Response.ContentType = ContentType;
                Response.AddHeader("content-disposition", "attachment;  filename=" + filename + "." + fileExtension);
                Response.BinaryWrite(bin);
                Response.End();
                <p>File Created</p>
            }
            catch (Exception e)
            {
                <p>@e.Message</p>
            }

        }
    </div>
</body>
</html>

After changing the file extension to .xlsm the file is generated but when I try to open the file in Excel I get an error saying that the extension isn't correct. I thought the only thing I would have to change would be the content type header but that's obviously not the issue. What else am I missing??? Any guidance would be appreciated!

This is the MVC 5 razor view code: ForestView.cshtml

@model Forest.Tree
@{
   var resultHtml = string.Empty;
 }
<div id="divTreeSearch>
@(Html.Kendo().PanelBar().
                         Name("panelbar")
                         .Items(panelbar =>
                                        {panelbar.Add()                                                   
                               .Content(@<text>@Html.Partial("_TreeSearch", Model, ViewData)</text>);}))
</div>
<div id="divTreeSearchResult">
@if(Model.TreeResultObj != null)
{
  resultHtml = Html.ContentFromPartial("_TreeReport", Model.TreeResultObj);

  @Html.Raw(resultHtml);    -- Not working
  @Html.Raw(HttpUtility.HtmlDecode(resultHtml)); -- Not Working
  Html.Raw(resultHtml);    -- Not working
  Html.Raw(HttpUtility.HtmlDecode(resultHtml)); -- Not Working

  Model.resultStringSaved  = resultHtml;
  @Html.DisplayText("resultStringSaved"); -- Not Working

   @Html.Raw("<text>Test</text>") -- Even this is not working

}

 @Html.Raw(Model.resultStringSaved) -- Not Working
 @Html.Raw(HttpUtility.HtmlDecode(Model.resultStringSaved)) -- Not Working
 @Html.DisplayText("resultStringSaved") -- Not Working

  @Html.Raw("<text>Test</text>") -- This is Working
</div>

ForestView.cshtml - @model Forest.Tree _TreeSearch.cshtml - @model Forest.Tree _TreeReport.cshtml - @model Forest.SearchData.Results

The projerty TreeResultObj in the model Forest.Tree is of type Forest.SearchData.Results

The ForestView.cshtml is the main view which loads initially and displays the search inputs from the _TreeSearch partial When search criteria entered and a 'search' button is clicked (all this is from the _TreeSearch) - a ajax call is make and the TreeSearch(id tree) action is called

The action again returns the main 'ForestView' - however now the model property 'TreeResultObj' is populated. so the code within the 'if conditon' in the 'ForestView' executed and calls another partial to get the content back as HTML string, which is saved in the 'resultHtml' variable

At this point I can see the Html Sting like "<Text>blah blah blah</text>" However trying to display the HTML string below the search panel in the main 'ForestView' is not working - I have tried almost every possible way.

Any text within the if condition is not rendered - it is an ajax call so there is no page refresh - I can see the HTML string value and also save it as a Model property but cannot get to display it in the main view. Any help would be much appreciated. Thanks in advance.