Here is the code that is causing the problem, it is inside the view:

@{
    if(item.Contract_Type != null)
    {
        dangerhtml = (item.Contract_Type == "Premium") ? "class=\"warning\"" : "";
    }
}
<td @dangerhtml>
    @Html.DisplayFor(modelItem => item.Contract_Type)
</td>

This code is sitting inside a foreach:

@foreach (var item in Model) {
..etc
}

It is throwing a NullReferenceException on the if line. The code works fine if I remove all the above and just do:

<td>
        @Html.DisplayFor(modelItem => item.Contract_Type)
</td>

But I am looking to set the class for the cell based on the contents of the item.Contract_Type

Any help appreciated!

I have a asp.net website that pulls information from a local database. The information is shown through a ListView. It has Edit, Update, Delete & Insert buttons.

What i wanna do is, use an Ajax UpdatePanel and make the Edit, Update and Insert buttons work without the whole page refreshing.

I know to only have Ajax work on certain triggers i need to do:-

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="false" >

So the first problem i face when i make triggers is that the ControlID of the buttons isnt being read/seen by the update panel and i get an error when i run it.

<AlternatingItemTemplate>
        <td runat="server" style="background-color:#FFF8DC; ">
            <tr>
            <td><b>13inch Price: </b><asp:Label ID="inch13priceLabel" runat="server" Text='<%# Eval("inch13price") %>' /></td>
            </tr>
            <tr>
            <td><asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete" OnClientClick="return confirm('Delete this Pizza?')" />
            <asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" OnClick="EditButton_Click"/></td>
            </tr>
        </td>
    </AlternatingItemTemplate>

I saw that i could use UpdatePanel1.Update() in code behind but that only updated the specified buttons and the other button such as Delete woudnt work.

So my question is:-

  1. How do i use the UpdatePanel correctly with the ListView when ChildrenAsTriggers="false"

OR

  1. How do i make the Delete button work if im using UpdatePanel1.Update() in my Codebehind file.

I'm absolutely beginner in ASP.NET MVC. Here what I'm trying to do for the main (home) page:

  • Get last 20 blog post.
  • Get list of the blog tags.

As I know it's impossible to use different models in same View, so I'm trying to make calls for different methods of the same repository and then show results. But the problems is - I don't know how to join results. Should I create new model and pass to View() or should I use partial view with different model? Here is the Controller code:

public ActionResult Index(ShortPostInfo m)
        {
            var top20 = PostRepository.GetLast20();
            var tag = PostRepository.GetTags();
            //How should I return to View() both top20 and tags?
            return View();
        }

I have an asp web application an I am using .net Web Security library to create users with method MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, out MembershipCreateStatus status);

Also I have bellow settings in my Web.config file

machineKey

<machineKey validationKey="52556EFC87C01645626E448147EDCE5AFD0BAC7D6C2E23FEDC789ED09C18ADBB81D52DDE60EDCC548CD4818249B197B364C2E7E287855E3F0C6BBB2A08F90CD5" decryptionKey="2A0BEA061F4A2AAAE75D6D4B0F97231F890332D2B10AED84AF6D0C5B09C38605" validation="SHA1" decryption="AES"/>

And

<add applicationName="MyApplication" name="SqlProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="LocalSqlServer" enablePasswordRetrieval="false" enablePasswordReset="true" requiresUniqueEmail="false" passwordFormat="Hashed" requiresQuestionAndAnswer="false" minRequiredPasswordLength="5" minRequiredNonalphanumericCharacters="0" maxInvalidPasswordAttempts="5"/>

I would like to ask if is it possible to decrypt the Asp Membership passwords if yes how can I do ?

If someone needs more information please let me know

Here is the code that is causing the problem, it is inside the view:

@{
    if(item.Contract_Type != null)
    {
        dangerhtml = (item.Contract_Type == "Premium") ? "class=\"warning\"" : "";
    }
}
<td @dangerhtml>
    @Html.DisplayFor(modelItem => item.Contract_Type)
</td>

It is throwing a NullReferenceException on the if line. The code works fine if I remove all the above and just do:

<td>
        @Html.DisplayFor(modelItem => item.Contract_Type)
</td>

But I am looking to set the class for the cell based on the contents of the item.Contract_Type

Any help appreciated!

I have a screen listing a load of imported bank transactions. Between 1 and 300 items can be displayed. When presented with the list, the user can select a category for each transaction. A list of categories could have well over a 100 options.

I would prefer not to have each row having the same data repeated in every drop down. 300 rows * 100 items in each drop down is a lot.

Is there a way I can share the same list of data between all the drop downs? So, one data source for all the selects?

I was thinking maybe with JavaScript, on 'drop down', fill it with data? But this too might be slow?

I'm going to be building a monitoring dashboard and one of the features needs to be the ability to add sql scripts on the fly. to add scripts via a page and without needing to recompile the application. Stored procedures are out of the question.

Im going to be using the sql results in data tables, and I need some kind of automatic data model & some how need to store the sql scripts.

Ideally using Dapper.

Everything ive looked into requires a code change each time a script is added.

Any examples much appreciated.

I am trying to reuse html helper found here

public static class HtmlHelperExtension
{
    public static string DatePickerDropDowns(this HtmlHelper html, string dayName, string monthName, string yearName)
    {
        var daysList = new TagBuilder("select");
        var monthsList = new TagBuilder("select");
        var yearsList = new TagBuilder("select");

        daysList.Attributes.Add("name", dayName);
        monthsList.Attributes.Add("name", monthName);
        yearsList.Attributes.Add("name", yearName);

        StringBuilder days = new StringBuilder();
        StringBuilder months = new StringBuilder();
        StringBuilder years = new StringBuilder();

        int beginYear = DateTime.UtcNow.Year - 100;
        int endYear = DateTime.UtcNow.Year;

        for (int i = 1; i <= 31; i++)
            days.AppendFormat("<option value='{0}'>{0}</option>", i);

        for (int i = 1; i <= 12; i++)
            months.AppendFormat("<option value='{0}'>{0}</option>", i);

        for (int i = beginYear; i <= endYear; i++)
            years.AppendFormat("<option value='{0}'>{0}</option>", i);

        daysList.InnerHtml = days.ToString();
        monthsList.InnerHtml = months.ToString();
        yearsList.InnerHtml = years.ToString();

        return string.Concat(daysList.ToString(), monthsList.ToString(), yearsList.ToString());
    }
}

but how do I use it on my mvc razor page .I tried by

@Html.DatePickerDropDowns("dayName","monthName","yearName")

but when I loaded my razor page ,it did n't worked ,it's just showing html syntax,I mean it's not showing up the actual dropdown lists. What I am I doing wrong here .how can I fix this and show three dropdowns 1 for day, 1 for month and 1 for years ?

I am adding to my dropdownlist the first day of the this month and the next two months, The problem is, when I tested this for November, it is going like that:

11/01/2014 12/01/2014 01/01/2014

AS you see, the 01/01/2014 is wrong, it needs to be 01/01/2014, I am not sure how to start this, any suggestions are appreciated. Thank you.

This is my code:

for (int i = 0; i < 3; i++)
{
    DateTime dt = DateTime.Now;
    DateTime dayone = new DateTime(dt.AddMonths(1).Year, dt.AddMonths(+i).Month, 1);
    DropDownList3.Items.Add(dayone.ToString("MM/dd/yyyy"));
}

I have created a RangeBar MS Chart control that binds with a datatable. The problem is that x axis is showing multiple points for same item with different range. enter image description here

Code

chChart.Series["Series1"].ChartType = SeriesChartType.RangeBar;
chChart.Series["Series1"].Points.DataBind(dt.DefaultView, "Number", "Start Time,Stop Time","ToolTip=Name,Label=Name");

Is there a way to group x axis value for same item so that the bars are in same line?

It throws the entire syntax as HTML On my mvc page This message popes up every time I hit save button.I can see my data gets saved successfully into the database,then it loads the view successfully and on top of the actual view it pops up a message with the entire html syntax of the page as html . please help me how to get rid of this error.

<!DOCTYPE html>

<meta charset="utf-8" />

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Index - My ASP.NET Application</title>

<link href="/Content/bootstrap.css" rel="stylesheet"/>

<script src="/Scripts/modernizr-2.6.2.js"></script>

<div class="navbar navbar-inverse navbar-fixed-top">

    <div class="container">

        <div class="navbar-header">

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                <span class="icon-bar"></span>

                <span class="icon-bar"></span>

                <span class="icon-bar"></span>

            </button>

            <a class="navbar-brand" href="/">Application name</a>

        </div>

        <div class="navbar-collapse collapse">

            <ul class="nav navbar-nav">

                <li><a href="/">Home</a></li>

                <li><a href="/Home/About">About</a></li>

                <li><a href="/Home/Contact">Contact</a></li>

            </ul>

            <form action="/Account/LogOff" class="navbar-right" id="logoutForm" method="post"><input name="__RequestVerificationToken" type="hidden" value="l_L2Ltz7nja-ziEI1EG66JS77qTRTdKUeRvc5rnh_-B2JYYg73lPm3MoX0JJqcvYK0GcFcHep_olY3HhRunJECYY6-YUGrtW5f7B3T7McH8jV3i10b7JITIZdtDq1zDV6aGw7E1QzBkdjh3HtKZpDw2" />    <ul class="nav navbar-nav navbar-right">

    <li>

        <a href="/Account/Manage" title="Manage">Hello user!</a>

    </li>

    <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>

</ul>

        </div>

    </div>

</div>

<div class="container body-content">

Index

First Name: Last Name: Cancel
    <hr />

    <footer>

        <p>&copy; 2014 - My ASP.NET Application</p>

    </footer>

</div>



<script src="/Scripts/bootstrap.js"></script>
<script src="/Scripts/mymvcscript.js"></script>
{"appName":"Firefox","requestId":"c80b400cb7d048de89222628bba3762c"}

I have an on premises .NET/IIS application for which I have developed new functionality to allow users to upload images to Azure Blob Storage. Everything works fine in my development environment, and now I am ready to deploy this application on premises to my production environment.

I can't figure out how to do this. Is it possible? If so, how do I do this?

A little more detail:

  • My environment is Windows Server 2008 R2 running IIS 7.5
  • The service connects to the actual Azure Blob Storage in the cloud, and I can save images online (that is, I log into my account on the Azure portal and I can see the images uploaded in my test container) from my development environment (VS 2013 with IIS Express) using the Azure Development Compute/Storage Emulator from Azure SDK 3.3.
  • I cannot get the solution working on my development box(es) using IIS 7.5.
  • I have tried "Deploy" the solution from the "Build" menu in my solution, but nothing happens. Attempting to "Publish" the Cloud Service Project in my solution just takes me to Azure to publish it online. Is that what is necessary to get my solution working? Publishing the Cloud Service project?

Thanks.

This question already has an answer here:

I will be using ASP.NET and SQL server express edition for a social networking site. Each user will post updates every now and then, and these updates must be kept in a database. Should I create a table for each user or should I store them all in one database with the users ID?

Individual Tables:
Pros:

  1. Faster searching. Less entries = Quicker searches
  2. Easy Maintenance. DROP TABLE Foo is more efficient than DELETE FROM Foobar WHERE ID = Bar

Cons:

  1. I think there's a limit on how many tables a database can have, and I plan on having around a 10 million users
  2. Millions of tables might be more of a performance bottleneck than a huge table with a billion users

Am I missing something? And what should I be doing based on my requirements?
Note: If there's something wrong with my post please tell me before downvoting!

I've got a separate project to my main MVC 4 web project to handle a database first model as generated by Entity Framework (4). I understand that this is a good idea, so that the data bits are even more loosely coupled from the application logic. I've added the data project's assembly reference, connection string and the System.Data.Entity reference to the main MVC 4 project to access the data. This works fine and as expected.

I would like to make use of the Razor scaffolding for creating default views such as Create or Edit, however the database project model is not being picked up by the scaffolding generator in the main application. The only way I've discovered to solve this is to drag the EDMX model file from the database project into the Models subfolder of the main project. After this, the scaffolding code appears to see the data definitions and works fine. This however has all the hallmarks of being the wrong thing to do (what happens when the database changes and you then have to maintain two definitions - kind of takes away the point of making the database access more loosely coupled).

Any ideas or rebukes for missing the obvious are welcome. Thanks - Phill

i'm having some problems with to pass value from UserProfile to @Viewbag to show in Index.cshtml.

Let's explain:

When i'm do a Register of new user or Login, i'm trying to pass UserType field from UserProfile in a viewbag. UserType is a custom field that i create on UserProfile to validate if the user is a "Musico" or "Ouvinte"

After debug application, I see that viewbag is taking NULL value.

This is the code that i try to get value from UserProfile in Register and Login post method:

LOGIN POST METHOD

[HttpPost] 
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
    if (ModelState.IsValid && WebSecurity.Login(model.UserName,
                                                model.Password,
                                                persistCookie: model.RememberMe))
    {
        var context = new UsersContext();
        var username = User.Identity.Name;
        var user = context.UserProfiles.SingleOrDefault(u => u.UserName == username);
        var userType = user.UserType;

        TempData["UserType"] = userType; //Taking UserType from User Profile
        return RedirectToLocal(returnUrl);
    }

    // If we got this far, something failed, redisplay form
    ModelState.AddModelError("", "The user name or password provided is incorrect.");
    return View(model); 
}

REGISTER POST METHOD

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
    if (ModelState.IsValid)
    {
        // Attempt to register the user
        try
        {
            var context = new UsersContext();
            var username = User.Identity.Name;
            var user = context.UserProfiles
                              .SingleOrDefault(u => u.UserName == username);
            var userType = user.UserType;
            WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new
            {
                UserType = model.UserType
            });
            WebSecurity.Login(model.UserName, model.Password);

            // string currentUserType = u.UserType;                    
            TempData["UserType"] = userType;//Get the userType to validate on _Layout
            return RedirectToAction("Index", "Home");
        }
        catch (MembershipCreateUserException e)
        {
            ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
        }
    }
    return View(model);
}

Calling viewbag in part of Index page

<p>
@if (Request.IsAuthenticated && ViewBag.UserType.equals("Musico")) 
{
    <span>musico</span>
}
else if (Request.IsAuthenticated && ViewBag.UserType.equals("Ouvinte"))
{
    <span>ouvinte</span>
}
else
{
    <span>teste</span>
}
</p>

HomeController

public ActionResult Index()
{
    ViewBag.UserType = TempData["UserType"];
    return View();
}

Partial view is not rendering while passing ViewModel.. Its rendering without ViewModel. I mean if I keep @Html.Partial("PartialClientIndex") then its rendering and when I pass ViewModel it directly going to Dispose without rendering partial view. I'm missing something here.. could you please help in this.

Main View:

    <div id="PartialClient">    
        @Html.Partial("PartialClientIndex", viewModelList)                     
   </div>

Action:

    [HttpPost]
    public ActionResult PartialClientIndex(int? SelectedGroupId)
    {
        int SkipRec = 0;
        int NextRec = 25;            
        VMClient vmclient = new VMClient();
        vmclient.IEClients = db.client.Where(cl => cl.Groups.id == SelectedGroupId).OrderBy(c => c.id).Skip(SkipRec).Take(NextRec).ToList();
        return PartialView("PartialClientIndex", vmclient);
    }

Partial View:

    @model IEnumerable<HostingManager.Models.VMClient>
   <table>
   <thead>
    <tr>
    <th style="width:25px; padding:10px;">
      Group
    </th>
    <th class="tbContent-Name">
        Client Name
    </th>
    <th class="tbContent-Name">
        Contact Person
    </th>
    <th class="tbContent-Name">
        Contact Email
    </th >        
    <th></th>
</tr>
</thead>
<tbody>
   @if(Model != null)        
   {
       var x = Model.Select(c=>c.IEClients).ToList();
       var y = x[0].ToList();

     //  var y = x[0]["item1"];
         foreach (var item in y) {
            <tr> 
                <td class="tbContent-Name">
                   @Html.DisplayFor(modelItem => item.Groups.name)
                </td>      
                <td class="tbContent-Name">
                    @Html.DisplayFor(modelItem => item.contactPerson)
                </td>
                <td class="tbContent-Name">
                    @Html.DisplayFor(modelItem => item.contactPerson)
                </td>
                <td class="tbContent-Name">
                    @Html.DisplayFor(modelItem => item.contactEmail)
                </td>        
                <td>
                    @Html.ActionLink("Edit", "Edit", new { id=item.id }) |          
                    @Html.ActionLink("Delete", "Delete", new { id = item.id }, new { onclick = "return confirm('Are you sure you wish to delete this ?');" })
                </td>
            </tr>
            }
            }
    </tbody>

I need limiting the number of checkboxes selected by user on the GridView in c# asp net.

I tried the code below but I have two problems:

  1. After alert popup 'Cannot check more than 3 check boxes' the Checkbox number four is always selected;
  2. The button btn is enabled and validate the form.

What am I missing?

What's wrong with this code?

Thank you in advance.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function CheckCheck() {
            var chkBoxList = document.getElementById('<%=GridView1.ClientID %>');
            var chkBoxCount = chkBoxList.getElementsByTagName("input");

            var btn = document.getElementById('<%=btn.ClientID %>');
            var i = 0;
            var tot = 0;
            for (i = 0; i < chkBoxCount.length; i++) {
                if (chkBoxCount[i].checked) {
                    tot = tot + 1;
                }
            }

            if (tot > 3) {
                alert('Cannot check more than 3 check boxes');
            }
        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="cbSelProduct" runat="server" onclick="javascript:CheckCheck();" />
                        <asp:HiddenField ID="HiddenField1" runat="server" Value='<%#Eval("name")%>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField ItemStyle-Width="250px" DataField="name" HeaderText="name" />
            </Columns>
        </asp:GridView>
        <asp:Button runat="server" ID="btn" Text="Send" OnClick="btn_Click" />
    </div>
    </form>
</body>
</html>

Resource not found error while trying to send URL of change password to registered email. I have checked the spelling and directories of my project. Everything is fine still I am getting that error.
This is the URL for sending email to registered users.

sbemailBody.Append("http://localhost/VirtualClassroom/Register/changePassword.aspx?uid=" +     Uniqueid);

When i click this link,I am getting that error.I am new to .Net.Please help.Thanks in advance

In Asp.net MVC 4, I want to make a html extend method.

I want it work like this:

in Razor View:

<button type='button' click='domethod'>click</button>
 @helper.minify(
    <script>
        function domethod() {
             alert('I'm script!');
        }
    </script>
 );

I think how can I make it render:

<button type='button' click='domethod'>click</button>
<script>function domethod() {alert('I'm script!');}</script>

May I create a extend in backcode, that it can recevie <script Tag> ?

We need to create a web application.the ui will be in pure html given by designers. We need to write the business logic and integrate the html. So what is the best we can use? Ajax web calls or mvc?

I'm add some css and js like:

// Single
bundles.Add(new ScriptBundle("~/res/js/single").Include(
    "~/res/js/jquery.js",// jQuery
));



// Main CSS
bundles.Add(new StyleBundle("~/res/css/css").Include(
      "~/res/css/MainStyle.css"
);

Then When I display it use:

@Styles.Render("~/res/css/single")
@Styles.Render("~/res/css/css")

It will display like this:

<link href="/res/css/css?v=-BDAI2AgglVOdcoS8Lr_ikUbMwTr-Vu9Jj0seHx5B81" rel="stylesheet"/>
<script src="/res/js/single?v=sbFboOuLdtmhD0n_uFzollmELtGkgdU5cTntphHFa-01"></script>

But I need it use full path, which mean include the base address on front. like:

<link href="http://www.xx.com/res/css/css?v=-BDAI2AgglVOdcoS8Lr_ikUbMwTr-Vu9Jj0seHx5B81" rel="stylesheet"/>
<script src="http://www.xx.com/res/js/single?v=sbFboOuLdtmhD0n_uFzollmELtGkgdU5cTntphHFa-01"></script>

So Is there a good way can display the full path. Why I do that? because maybe I want cache the js, css. use other domain name. only for CDN. maybe I will change the base domain to CDN domain...