I am having a multiselect dropdown, the value for the dropdown is coming from the database. how to populate the multiselect dropdown with more than one selected value.

my viewbag in controller

var app_dependent = (from ao in db.mas_app_dependent
                     where ao.app_key == id   // id is app_key(PK) value=1
                     select ao.app_dependent__key).ToList();
 ViewBag.app_key = new SelectList(db.mas_apps, "app_key", "app_name", app_dependent);

my view in index.cshtml page

 <div class="form-group">
  <label id="ownerbiz" class="control-label col-md-2">Dependent Application</label>
  <div class="col-md-10">
@Html.DropDownList("app_key", null, "--Select--", htmlAttributes: new { @class = "form-control e1", @multiple = "multiple", @placeholder = "Select / Search here!" })
  </div>

my db.mas_apps table value

  app_key(PK)  app_name
        1        CRTS
        2        CITRIX
        12       Hiport
        15       Frig

my db.mas_app_dependent values for the variable app_dependent

dep_key(PK) app_key dependent_app_key
1           1         2 
12          1         12    

I've looked at the related questions and followed their solutions, but it's still isn't working for me. Any help is appreciated, thank you.

I have a web application added as a virtual directory (under the parent site) and converted into an application. It even has its own application pool. The parent is .net 2.0 and child is .net 4.0.

The parent's Web.Config:

<configuration>
    <configSections>
        <sectionGroup name="system.web.extensions" ...>
            <sectionGroup name="scripting" ...>
                <section name="scriptResourceHandler" ... />
                <sectionGroup name="webServices" ...>
                    <section name="jsonSerialization" ... />
                    <section name="profileService" ... />
                    <section name="authenticationService" ... />
                </sectionGroup>
            </sectionGroup>
        </sectionGroup>
    </configSections>
    ...
</configuration>

Child's Web.Config

<configurations>
    <configSections>
            <clear/>      
    </configSections>
    <connectionStrings>
        ...
    </connectionStrings>
</configuration>

My error message:

There is a duplicate 'system.web.extensions/scripting/scriptResourceHandler' section defined

The doesn't work. I've also tried referencing the system.web.extensions block outside of , and wrapping it in

and it still doesn't work.

I've also tried removing those sections in the child's Web.Config and it still doesn't work:

<configurations>
    <configSections>
            <remove name="system.web.extensions" />     
    </configSections>
    <connectionStrings>
        ...
    </connectionStrings>
</configuration>

At this point, I don't know what else to try. Is there a way to separate the child web application completely from the parent, but still retaining the parent's domain? I.E. I want to be able to access the child's website through www.parent.com/child.

Thanks again.

In my ASP.NET page I have a search box that is currently working as expected. What I would like to do is leave the searched value in that textbox after searching (the search opens a new page, though I'm retaining the search value from querystring). I can confirm the variable is being retained correctly by using the value <%= search%> in my aspx, however when I try to show that in my textbox nothing displays. I have searched dozens of forum posts and the nearest I can tell is that I need to databind this textbox. I'm not sure where my mistake is, but this is the closest I have come up with:

<asp:TextBox ID="SearchTextBox" runat="server" Text='<%# search %>'></asp:TextBox>
Search: <%=search %>

With the code behind

public string search;

protected void Page_Load(object sender, EventArgs e)
{
    search = Request.QueryString["search"];
    SearchTextBox.Text = search;
    Page.DataBind();
}

I am currently using the repository pattern where I have my data models behind a repository that return my domain models. I am using dependency injection to do all of this. My problem is, let's say I have a domain model Student which I get from my StudentRepository. Student may have properties on it that I use in some places, but not others, for example, Courses:

public class Student
{
    public int ID { get; private set; }
    public string Name { get; private set; }

    public Student(int id, string name, IEnumberable courses = null)
    {
        ID = id;
        Name = name;
        _courses = courses;
    }

    private IEnumerable<Course> _courses;

    public IEnumerable<Course> Courses()
    {
        if(_courses == null)
        {
            // I need a good way to load the CourseRepository
            _courses = CourseRepository.GetCoursesByStudentID(ID);
        }

        return _courses;
    }
}

Therefore, I want this type of lazy loading set up but I do not know how I can do it elegantly, and is difficult for me to understand how I can load the implementation of the CourseRepository (or ICourseRepository using DI), where my repository looks like:

public class CourseRepository : ICourseRepository
{
    private DbContext _db;

    public CourseRepository(DbContext db)
    {
        _db = db;
    }

    public IEnumerable<DomainModels.Course> GetCoursesByStudentID(int studentID)
    {
        return CourseFactory.Build(_db.Courses.Where(c=>c.StudentID == studentID));
    }
}

This is not critical for an answer, but it would help if the solution were relative to Ninject since that is my current DI container.

I have a rule in my web.config that works.

<rule name="Guestbook Rewrite" stopProcessing="true">
<match url="(.*?)-guestbook" />
<action type="Rewrite" url="guestbook.asp?gb={R:1}" />
</rule>

When someone goes to MyDomain.com/view-guestbook or MyDomain.com/sign-guestbook they go to the appropriate pages.

What I am having difficulty with is that I have several pages of guestbook entries, so I want to be able to add a rule so that when someone goes to “view-guestbook-page-9” they are actually getting MyDomain.com/guestbook.asp?gb=view&pagenum=9. I had added the following rule, but as soon as I did I got 500 errors. I am going to guess that either it is in conflict with the previous rule or the syntax is incorrect.

<rule name="Guestbook View Page Rewrite" stopProcessing="true">
<match url="view-guestbook-page-(.*)" />
<action type="Rewrite" url="guestbook.asp?gb=view&pagenum={R:1}" />
</rule>

How can I have both rules or a single rule that would solve both?

In past projects, I've used .NET AntiForgeryToken to protect form submissions.

Now, I'm doing things a bit differently - I have a Web API on the server, and the client app is purely HTML/CSS/JS - no ASP.NET in sight. Authentication is now OWIN, token-based.

Really I just want a sanity check - is AntiForgeryToken a thing of the past I have now outgrown? Are there any other security precautions I need in place of it?

I have a web page with:

  • a RadGrid
  • a RadListView
  • a save button
  • Various other controls to display and update other data

My new requirement is the following:

If a user clicks the save button and there are any pending inserts in the RadGrid or the RadListView, then finish inserting them. In other words, the buttons I'm showing below in the grids' insert form has not been clicked.

Currently, the RadGrid insert doesn't insert to the database until it's own save button is clicked: enter image description here

The same is true with the RadListView though the button looks slightly different: enter image description here

Is there a way for me to call the InsertCommand of each grid from the save button that is outside of the grids?

so i want to have a button the changes the text of a label when i click it and it says page not available, but when i comment out the update panel it atleast shows up.

   <form id="form1" runat="server">
    <asp:ScriptManager ID="s1" runat = "server"></asp:ScriptManager>
<div>
<h1>UpDaTe PaNeL tEsT PaGe</h1>
start text : Hello <br />
updated text: World<br />
    <hr />

<asp:UpdatePanel ID="p1" runat="server">
    <ContentTemplate>
  <asp:Button ID="Button1" runat="server" Text="Update"  OnClick="updateLabel" Height="29px" Width="110px"/> -->
        Text: <asp:Label ID="Label1" runat="server" Text="hello"></asp:Label>

    </ContentTemplate>
</asp:UpdatePanel>    
</div>
</form>

codebehind

   Public Class aaaa
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub

Function updatelabel() As String
    Label1.Text = "World"
End Function
End Class

This issue continues to be a problem. I see several similar posts but they are all now a couple of years old.
I have referenced Google Apis via Nuget and now I am, quite frankly, in "Nuget hell". First, a rant, why so many assemblies and references when you use Nuget, what is the purpose of the .NET Framework? For example, why do I see a copy of System.IO DLL in my /bin folder? I struggled for awhile just to get my website to run any of my code. After I upgraded all of my assemblies to 4.0, and after I ran updates on my local .Net install running on Windows 8.1, I have my local dev website working again. When I call any page on my site that calls the Google drive assembly code, I get this error:

Could not load file or assembly 'System.Net.Http.Primitives,
Version=1.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its 
dependencies. The located assembly's manifest definition does not match the
assembly reference. (Exception from HRESULT: 0x80131040)

I've been round and round with the suggestions to map assemblies from this post: Google Drive SDK System.Net.Http.Primitives Version 1.5.0.0 instead of 2.1.10.0 And either it doesn't work, or I do not have the correct assembly mappings. I'm really at a loss.

I have compiled my Google Drive code and assembly separate of my web application assemblie(s). My Google Drive code is working perfect and I only have an issue when I try to reference this project from my web application.

I can't find any additional tips here or from Google. I am stuck.

I'm looking to post formdata to a c# web api and have the model binding work. This looks like it should be possible, but my object is never populated. I want to keep the code simple and flexible. ie. i dont want to add a new json attribute to my ajax call every time i add a new form field and i would like to pass files if i wish to (not expecting files to bind to the model).

Here is basically what I have at the moment.

    $('.save').click(function () {
        $.ajax({
            url: 'api/plant/insert")',
            data: new FormData($('form')[0]),
            type: 'POST',
            processData: false,
            contentType: 'application/x-www-form-urlencoded',
            beforeSend: function () {
                $.processing({ content: 'Saving Plant' });
            },
            error: function () {
                $.error({ content: 'An error occurred saving the plant' });
            },
            success: function (data) {
                location.assign('PlantEdit.cshtml?plant_id=' + data);
            }
        });
    });

and in my controller

    public int Insert([FromBody] Plant plant)
    {
        return plant.Insert();
    }

The result is the plant instance is not null, but all attributes are null, hence an empty row inserted into the database. So am I asking for too much, or am I going about this all wrong?

In an index.cshtml I have the following working code similar to:

<script type="text/javascript">

if ('@Model.SomeCondition' === 'True'){
Do Something();
}

</script>

The === 'True' seems like an odd hack to me to force Razor and JavaScript to get along. How can I refactor to use === true? This doesn't give the same result. Can this be done with Razor and JavaScript?

I have an input text field "NameTxt". Default value of the "Emaillist" is coming from Model.

Based on the input text, I would like to update my "Emaillist".

For example if i give "an" in "NameTxt", then my "Emaillist" should show all emails having "an" in their emails. How can i do this in Java Script?

   <input id="NameTxt" class="tbox" type="text" value="" name="NameTxt" placeholder="Enter Name" />

   <div id="Emaillist">
       @foreach (var names in @Model.UserList)
       {
           var checkBoxId = "chk" + names.Value;
           var tdId = "td" + names.Value;
           <table>
               <tr>
                 <td width="20px">
                    <input type="checkbox" id="@checkBoxId" class="chkclass" value="@names.Value" />
                  </td>
                  <td id="@tdId" width="100px">
                       @names.Text
                  </td>
                </tr>
              </table>
             }
         </div>

I have to stickthrough text which is div based on condition. if @MemberAddressDetails.Status is 'Bad' I have to strick all of the blow <div> text. Can we do this with css class?

  <div>@MemberAddressDetails.JobTitle</div>
  <div>@MemberAddressDetails.CompanyName</div>
  <div>@MemberAddressDetails.Country</div>
  <div>@MemberAddressDetails.AddressLine1</div>

I can insert class name in based on condition. that's why I am asking for div class.

We currently have a very large application that has developed over many years based on WebForms, and are looking for a sensible way to migrate to an MVC-style solution.

Our current overall structure looks like this:

  • SQL Server Database - all calls are made to Stored Procs from the Data Access Layer

  • Data Access layer - sends XML requests to SQL back end, and receives XML response from back end

  • Business/Application layer - currently WebForms, several rich UserControls, GUI helper classes, and Business classes

  • Front End - HTML/JSON/Javascript with heavy AJAX emphasis

In WebForms, we loaded the XML returned from the DAL method into an XML DOM and then populated the form using transitional XML DOM parsing. However, in moving to Razor Views, our concern is that we have to create a class for every single database hit that is made. We currently have 400 unique stored procs that are called from our DAL, and it seems impractical to create 400 classes simply so that we can use Razor templating. To complicate matters, a lot of our forms are user-definable (the user chooses the tabs/fields/field types/layout) so the form is very dynamic and customizable. All of the samples using Razor seem to fit a very static type of class definition and form layout.

So my question is - are Razor Views completely impractical for what we are trying to accomplish?

I am trying to get my head around drop down lists with MVC, which appears to be failing me. I've been tinkering with the code shown below but can't get it right.

What I am trying to achieve is simple - hard coding some drop down options in the controller, have them appear in the Razor rendered html and when an option is selected, that selected value is bound back to the string property in the model.

With the code below I can't access li from within the View.

I've seen other guides but I haven't been able to make it work, is binding model the best option for me, given what I'm trying to achieve, or would ViewBag etc be better?

Could someone show me where I'm going wrong please?

Model

public class ViewModel {
    public string MyOption { get; set; } }

View

@model ViewModel
@Html.DropDownListFor(m => m.MyOption, li, "--Select--")

Controller

public ActionResult Index()
        {
            List<SelectListItem> li = new List<SelectListItem>();
            li.Add(new SelectListItem { Text = "Option One", Value = "option1" });
            li.Add(new SelectListItem { Text = "Option Two", Value = "option2" });
            return View(li);
        }

I am checking condition and still throwing exception. Is there any otherway to check null?

  <div>@(MemberAddressDetails.CompanyName== null?"":MemberAddressDetails.CompanyName)</div>

enter image description here

I have problems with sessions in asp.net. I searched the web for a while, but couldn't find the reason why it doesn't works. The session disappears after some minutes. It is a project that isn't created by myself, i'm not a hero in aspx. But I'm trying to solve this problem.

Web.config

 <system.web>   
    <customErrors mode="RemoteOnly"/>
    <httpRuntime requestValidationMode="2.0"/>
    <pages validateRequest="false" />

    <sessionState mode="InProc" cookieless="false" timeout="120"  />

  </system.web>

Checking if Logged in

public static bool isLoggedIn(HttpSessionState session)
        {
            return session["user"] != null;
        }

Not logged in ? Showing login form, filling in the form and then send it to server to check

password = FormsAuthentication.HashPasswordForStoringInConfigFile(
                        password,
                        "SHA1");
                    UserService gs = new UserService();
                    user g = gs.getUserByLogin(username, password);

GetUserByLogin function in userservice

public user getUserByLogin(string username, string password)
        {
            user g;
            var db = new projectName.Db.Models.projectnetContext();

            IQueryable<user> query = from gb in db.users
                where gb.username.Equals(username)
                      && gb.Passwoord.Equals(password.ToLower())
                      && gb.Status == 1
                select gb;

            if (!query.Any())
                g = null;
            else
                g = query.First();

            return g;
        }

After login in, creating the session

Session["user"] = g;

My problem is that I have set the time-out. But it doesn't seems to work. If I check the timeout on the server, it is set to 120. But after 2 minutes, I'm redirected to the login form. Can I solve this? If I debug on localhost, It seems to work, but not online.

Or if it isn't possible, Cookies? Normally I work with cookies in PHP,.. But is there a way to do it in ASP.NET on a safe way?

I'm trying to set a value in a foreach but i get the error that it dosent exist in the current contect.

Here is my code;

    @{
        string sUsr = System.Web.HttpContext.Current.Request.ServerVariables["AUTH_USER"].ToLower();
        var db = Database.Open("SQLServerConnectionString");
        var selectUser = "SELECT * FROM USERS WHERE username = " + @sUsr;

        }
    @foreach (var userid in db.Query(selectUser)) 
                            {
                                var sReg = userid.userdisplayname;
                                var sAns = userid.usersign;
                                var smail = userid.usermail;
                            }
 ...some html code etc.

    @sReg   <---- The name sReg dosent exist in the current context

If i try with the folowing code it works and Hello World is rendered in my webpage

    @{ var myMessage =  "Hello World"; }

 ...some html code etc.

    @myMessage

I found something like <%=Html.SnapbackLink("linkText", "actionName") %><br /><br /> in my project code.It would be helpful if someone explains? what it is and when to use that?

I have a text box

<input type="text" id="mytextbox" name="searchField"/>

and three radio buttons. I need to mask text box on select of specific radio button selection. I have successfully done with it. But on third radio button I want text box to just clear without any masking, just an open field. So, if we select Radio button 1, Text Box will masked accordingly but then we select Radio button 3. Masking remain in place. I want to remove it then.

Forgive the bad English. Thanks is advance.

Code used for masking.

$("#mytextbox").mask("999-9999-9999");

On the client side, it will be logged when StateChanged event is triggered

But this afternoon, at 14:05, I found out that Hub's OnDisconnected method was called by the client, and there is no log about connection state changes from OnConnect to Disconnect.

2015-06-02 04:59:58.961
ConnectiId:ace39fd7-981d-4860-a0d8-752b8a37fec4
OldState:Connected
NewState:Reconnecting



2015-06-02 05:00:00.599
ConnectiId:ace39fd7-981d-4860-a0d8-752b8a37fec4
OldState:Reconnecting
NewState:Connected

Wouldn't StateChanged event be triggered if the client calls to disconnect?