I am displaying a form in pop up using window.showmodeldialog. The form which is being displayed in pop up contains multiple panels.I want to show/hide panel on the basis of dropdown value supplied as a parameter. Please help.

DropDown value to be selected

Value Selected

Pop up Opened on the basis of selected value

This question already has an answer here:

Is there a C# DateTime extension that replicates moment.js framework fromNow() and toNow()? I tried a web search and couldn't find anything.

This is a code to add,update and view employee details by creating database at the back end.I have given only the c# Coding.There are four layers which are created.I don't understand the code that each layer does.Please explain the code in just simple words or by creating comments so that I can understand.There is also a wcf service at the end which is added as a web reference.Apart form the four layers webpages for insert,update and view are also given.The webpages contain a source information and the page load information.

public DataTable AddStatus(string procRoles)
{
    SqlConnection con = connect.RetriveConnection();
    try
    {
        con.Open();
        command = new SqlCommand(procRoles, con);
        command.CommandType = CommandType.StoredProcedure;
        adapter.SelectCommand = command;
        command.ExecuteNonQuery();
        adapter.Fill(dtStatus);
        command.Dispose();
        return dtStatus;
    }
    catch (SqlException custException)
    {
        throw (custException);
    }
    finally
    {
        command.Dispose();
        adapter.Dispose();
        con.Close();
    }
}

//PageLoad event

EmployeeController processing = new EmployeeController();
protected void Page_Load(object sender, EventArgs e)
{
    Calendar1.Visible = false;
    lblAdd.Visible = false;
    lblMax.Visible=false;

    if (!IsPostBack)
    {
        //columnName
        DataTable dt_ddselect = processing.Gender();
        ddlG.DataSource = dt_ddselect;
        ddlG.Items.Clear();
        ddlG.AppendDataBoundItems = true;
        ddlG.DataTextField = "Gender";
        ddlG.DataBind();
        //columnName
        DataTable dtstatus = processing.Status();
        ddlStatus.DataSource = dtstatus;
        ddlStatus.Items.Clear();
        ddlStatus.AppendDataBoundItems = true;
        ddlStatus.DataTextField = "Status";
        ddlStatus.DataBind();
    }
}

Im trying to make a global variable so other pages can do stuff with it. How do i make a variable global in unity DI mvc applicaton.

Note: this approach can not make me happy.

These are my models:

public class Post
{
    [Key]
    public int Id { get; set; }

    public string Title { get; set; }

    [DefaultValue(null)]
    public virtual Image Thumbnail { get; set; }

    public void SetViewModelValues(CreatePostViewModel viewModel)
    {
        Title = viewModel.Title;
    }
}

public class CreatePostViewModel
{
    public string Title { get; set; }

    public int? ThumbnailId { get; set; }
}

And the action:

    public ActionResult CreatePost(CreatePostViewModel postViewModel, int? id)
    {
        Post post;

        if (id != null)
        {
            post = dbWebContent.Posts.Find(id);
            if (post == null)
                return HttpNotFound();
        }
        else
        {
            post = new Post();
        }

        if (!ModelState.IsValid)
            return View(post);

        post.SetViewModelValues(postViewModel);
        post.Thumbnail = null; // Even setting null doesn't work

        var state = (post.Id == 0) ? EntityState.Added : EntityState.Modified;
        dbWebContent.Entry(post).State = state;

        if (dbWebContent.SaveChanges() > 0)
        {
            ViewBag.Success = true;
            return View(post);
        }

        ViewBag.ErrorMessage = "Error!";
        return View(post);
    }

The problem is that when I try to update Thumbnail property it doesn't make any change in the database. SaveChanges method returns 1 (even if Thumbnail is the only modified property). Even when I try to set it to null. Everything works when creating new post. But editing is not working. What is the problem? Is there any better solution to handle Add/Update operations in one action?

These are not all my properties in Post class (no other foreign keys). The second question is: is there any better way for creating an entity from view model? I mean do I need to store all these properties values in two separate objects and then copy it from view model to entity or is there any prettier way to do that?

I have 2 asp.net applications , I want to share session between the two applications. on my localhost i added 2 entries in the host file for the 2 subdomains say (test1.test.com) and (test2.test.com). In each of the applications i changed the web.config with

<httpCookies domain=".test.com">

also I changed the machine key as following

<machineKey validationKey="3FC58E938A92B609AB264D18C4A494CEB2A01100C7FE71AC6B41DD5372458D8265C5D06E72CC67F1F0AD58B8713DFDB0A8058861D39F47B5AA65310C8C45107D" decryptionKey="C24521F47AEAB67CC40F679632975C91AC0FCBD9A2E173B3" validation="SHA1" />

but i did not get the expected result (session is not shared between the 2 applications)

did i miss something?

I have a stored procedure that I know might take some time to execute. When I run it from the "SQL Server Management Studio" it takes about 12-15 minutes to complete and that is fine, but when I run it from my C# asp.net web application it crashes after 40 minutes and it still doesn't complete.

What it the difference between the two runs and how can I fix it to run from my application?

I am using MVC4 and razor view. I am binding a list of items in the page. I want to post back a single item after clicking the specific row. e.g.

ID    FName   LName
1     xxxx    xxxx
2     xxxx    xxxx

When the user clicks "1" (the first row) it should post back the entire row to the server. Where "1" is a link or a button.

I have tried with

<a href='@Url.Action("MethodName", "ControllerName", Object)'>
  1
</a>

but it is passing the values in the url which i don't want. Is it good to surround each with element? Any otherway?

Please Note: It should not be the ajax way and it should not post back as query string.

Thanks!

i need to set arabic numbers on y axis for my asp.net chart, but unfortunately changing the font would not help me. So i tried to change the label text by Code, for all labels I want to change the TEXT of labels, is it possible, is there any way? thanks

I'm using ASP.net MVC 5 with Razor Engine. I want to create a page to register users . I create a Model and MetaData model for my User entity . All my codes are here . I think everything is Ok but I got this compile error :

Compiler Error Message: CS1061: 'NP1.ViewModels.RegisterVM' does not contain a definition for 'UserEmail' and no extension method 'UserEmail' accepting a first argument of type 'NP1.ViewModels.RegisterVM' could be found (are you missing a using directive or an assembly reference?)

Could anyone help me how fix it,please ?

User.cs

namespace NP1.Models
 {
   using System;
   using System.Collections.Generic;

public partial class User
{
    public int UserID { get; set; }
    public string UserEmail { get; set; }
    public string UserFirstName { get; set; }
    public string UserLastName { get; set; }
    public string UserPassWord { get; set; }
    public string UserCellPhone { get; set; }
    public string UserTell { get; set; }
    public string UserImage { get; set; }
    public string UserAddress { get; set; }
    public Nullable<byte> UserStatus { get; set; }
    public Nullable<System.DateTime> UserBirthDate { get; set; }
    public string UserGender { get; set; }
   }
 }

UserMetaData.cs

namespace NP1.Models.MetaData
   {
  internal class UserMetaData
   {
    [ScaffoldColumn(false)]
    [Bindable(false)]
    public int UserID { get; set; }

    [Required(ErrorMessage = "plz add your Email", AllowEmptyStrings = false)]
    [DisplayName("Email")]
    [Display(Name = "Email")]
    [RegularExpression(@"^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,4})$", ErrorMessage = "add your email correctly")]
    public string UserEmail { get; set; }

    [Required(ErrorMessage="add your name",AllowEmptyStrings=false)]
    [DisplayName("Name")]
    [Display(Name = "Name")]
    [StringLength(50,ErrorMessage="Name should be 50 character")]
    public string UserFirstName { get; set; }

    public string UserLastName { get; set; }

    [Required(ErrorMessage = "Add password",AllowEmptyStrings=false)]
    [Display(Name = "password")]
    [DisplayName("password")]
    [DataType(DataType.Password)]
    public string UserPassWord { get; set; }

    [Display(Name = "Cellphone")]
    [DisplayName("Cellphone")]
    [RegularExpression(@"^0?9[123]\d{8}$", ErrorMessage = "add Cellphone correctly")]
    [StringLength(11, ErrorMessage = "Cellphone should be 11 character")]
    public string UserCellPhone { get; set; }

    [Display(Name = "phoneNumber")]
    [DisplayName("phoneNumber")]
    [StringLength(11, ErrorMessage = "phoneNumber should be 11 character")]
    public string UserTell { get; set; }

    public string UserImage { get; set; }
    public string UserAddress { get; set; }

    [ScaffoldColumn(false)]
    [Display(Name = "Status")]
    [DisplayName("Status")]
    public Nullable<byte> UserStatus { get; set; }

    [Display(Name = "BirthDate")]
    [DisplayName("BirthDate")]
    public Nullable<System.DateTime> UserBirthDate { get; set; }

    [Display(Name = "Gender")]
    [DisplayName("Gender")]


    public string UserGender { get; set; }
     } 
 }
     namespace NP1.Models
     {
      [MetadataType(typeof(NP1.Models.MetaData.UserMetaData))]
      public partial class User
      {

      }
  }

RegisterVM

public class RegisterVM
{
    public List<SocialNetwork> SocialNetworks { get; set; }
    public List<Footer> Footers { get; set; }
    public List<FooterMenu> FooterMenus { get; set; }
    public List<User> Users { get; set; }

}

Register.cs

    @model NP1.ViewModels.RegisterVM

    @{
      ViewBag.Title = "Register";
     }

  @using (Html.BeginForm()) 
   {
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>User</h4>
    <hr />
    @Html.ValidationSummary(true)

    <div class="form-group">
        @Html.LabelFor(model => model.UserEmail, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserEmail)
            @Html.ValidationMessageFor(model => model.UserEmail)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UserFirstName, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserFirstName)
            @Html.ValidationMessageFor(model => model.UserFirstName)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UserLastName, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserLastName)
            @Html.ValidationMessageFor(model => model.UserLastName)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UserPassWord, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserPassWord)
            @Html.ValidationMessageFor(model => model.UserPassWord)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UserCellPhone, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserCellPhone)
            @Html.ValidationMessageFor(model => model.UserCellPhone)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UserTell, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserTell)
            @Html.ValidationMessageFor(model => model.UserTell)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UserImage, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserImage)
            @Html.ValidationMessageFor(model => model.UserImage)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UserAddress, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserAddress)
            @Html.ValidationMessageFor(model => model.UserAddress)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UserStatus, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserStatus)
            @Html.ValidationMessageFor(model => model.UserStatus)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UserBirthDate, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserBirthDate)
            @Html.ValidationMessageFor(model => model.UserBirthDate)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UserGender, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.UserGender)
            @Html.ValidationMessageFor(model => model.UserGender)
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
 }

  <div>
    @Html.ActionLink("Back to List", "Index")
  </div>

  • ASP.NET 4.51, WebForms, VS2013

I am using Quartz.NET to do some background processing where ultimately I make a connection to my SQL Server. This all works locally on my development machine against IIS Express, but when I deploy it to my staging server running IIS I run into problems.

The code to connect to the database could not be simpler:

myConnection = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=MyDB;User ID=sa;Password=myPass");

however this throws an exception of:

System.Data.SqlClient.SqlException: Login failed for user 'IIS APPPOOL\somehost.somedomain.com'.

I am 100% confident the connection string is correct as when used in a normal page it works just fine. So what is throwing me is the reference to IIS APPPOOL.

Is the SqlConnection somehow not using the connection string it was passed? Doing some form of weird user impersonation when the connection is being made?

Put another way. How do I make the SqlConnection() work from within the thread when I know the connection string is correct?

I am trying to build a simple login system from the ground up, using the code-first approach with ASP.NET MVC v5, Entity Framework v7, and Identity v3. I'm modeling my app after the ASP.NET MVC app with individual user logins template that Visual Studio comes with.

All I want is for the user to create an account, and for that account to be saved in a database.

Here is the code I have so far:

Startup.cs:

public class Startup
{
    public IConfigurationRoot Configuration { get; set; }
    public Startup()
    {
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json");
        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());
        app.UseStaticFiles();
        app.UseIdentity();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

    public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}

appsettings.json contains this code for the connection to the database:

"Data": {
  "DefaultConnection": {
    "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=SimpleAuthenticationApp;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

Here's the code for the Register POST action in Controllers/AccountController.cs:

    [HttpPost]
    public async Task<IActionResult> Register (RegisterViewModel model)
    {
        try
        {
            var user = new ApplicationUser { UserName = model.Email };
            IdentityResult result = await _userManager.CreateAsync(user, model.Password);
            Console.WriteLine(result);
            return View("Home", "Index");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            return View();
        }
    }

In this code, RegisterViewModel is just a ViewModel with fields for Email, Password, and ConfirmPassword. The Account/Register view is just a form that asks for these fields. ApplicationUser is a class that extends from IdentityUser.

In the POST route, I set a break point at the try block, and when it enters the catch block, the exception reads "Invalid object name AspNetUsers."

Before I create the first user in this app, there's no database. I register a new user, the app takes me to an error page reading, "Applying existing migrations for ApplicationDbContext may resolve this issue" with a button to apply migrations. When I hit the button, the database is created. I've noticed that when I run the default MVC with Users app, there's a Migrations folder containing 00000000000000_CreateIdentitySchema.cs and ApplicationDbContextModelSnapshot.cs that look like they contain the settings to create the database with tables needed. I tried using those files in my app, but it didn't make any difference.

My questions:

  • How does Identity/Entity Framework create the database with tables for user information? It seems strange that I need to "Apply migrations" before the database for the app can be created.

  • What can I do in my own app to get a simple user login working? Other approaches or frameworks are welcome.

I have a list of names with an edit button next to it. When the edit button is clicked, the actionresult loads a partial for edit and fills in the name in an textbox. On this partial I also have a drop down list that shows a list of file names of images. I have jquery code for the change event to show a little image of the selected one. When I change the drop down selection, that works just fine. But when I click on the edit button and the name is filled in the textbox and the selection of the dropdown is set via the model, the change event is not triggered.

Is it possible to trigger a change event on a drop down list if the selection changes but not by the user?

Can you trigger a jquery function within an @if (...) {...} line in the razor.

For example:

@if (m=>m.image.length >0)
{
   //do something here to trigger the change event of the drop down list
}

any help would be great!!

I'm basically creating an edit form page. And what I have is a few comboboxes that are being populated with possible selected value. What I want to do is set the text to the current value. My curve ball is this. The edit form datasource is coming from DataSourceA the combobox is coming from DataSourceB. How do I get the combobox text to be the value of DataSourceA on binding?

I have my models

public class Post
{
    [Key]
    public int Id { get; set; }

    public string Title { get; set; }

    public string Description { get; set; }
}

public class Photo
{
    [Key]
    public int Id { get; set; }

    public string Title { get; set; }

    public string Description { get; set; }

    public string Source { get; set; }
}

public class PhotoAttach
{
    [Key]
    public int Id { get; set; }

    public virtual Post Post { get; set; }

    public virtual Photo Photo { get; set; }

    public bool IsThumbnail { get; set; }
}

In my CreatePost view, I want user to be able to select some existing photos to be attached to creating post. I made this using some scripts, so when user clicks submit button I already have a JSON object containing all photos ids that are going to be attached.

But this view uses Post as the model. So how can I refer to this object from controller?

I though about converting it to a string and adding some hidden input. But is it possible to access this from the controller?

Is there any way to do that without creating new view model?

I am working on ASP.NET MVC4, web API and I tried to write Password encryption code In Register controller I wrote this code

 namespace PasswordHash.Controllers
{
    public class RegisterController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        //POST api/values
        public HttpResponseMessage Post(user user)
        {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
            var db = new passwordhashEntities();
            var checkExitUser = (from c in db.users where c.UserName == user.UserName select c).Count();
            if (checkExitUser == 0)
            {
                var newUser = new user()
                {
                    Email = user.Email,
                    UserName = user.UserName,
                    Password = PasswordHashHelper.CreateHash(user.Password),
                    PostCode = user.PostCode,
                    SlowHash = user.SlowHash


                };
                db.users.Add(newUser);
                db.SaveChanges();
                response.Content = new StringContent("Resgister successfully ", Encoding.Unicode);
            }
            else
                response.Content = new StringContent(user.UserName + "is exit", Encoding.Unicode);

            return response;
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }
}

the run time error apear in this line : var checkExitUser = (from c in db.users where c.UserName == user.UserName select c).Count(); the error is : An exception of type 'System.Data.EntityException' occurred in System.Data.Entity.dll but was not handled in user code

I think I need to install some tools or programs, but I do not know what is this tool? because I tried to apply other encryption tutorials and also It did not work with me with same error.

I'm writing an API for mobile clients and an AngularJS web front end using ASP.NET 5. Everything's going well, but I'm stumped on how to create a POST to upload files to the server.

The best info I've found is in this thread. Based on the research I've done, I want to do something like the following, but I keep getting shot down by VS2015 and it's inability to find proper references.

    [HttpPost("card/{cardId}/image")]
    public async Task<IActionResult> Upload()
    {
        var provider = new MultipartMemoryStreamProvider();
        await Request.Body.ReadAsMultipartAsync(provider);
        foreach (var file in provider.Contents)
        {
            var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
            var buffer = await file.ReadAsByteArrayAsync();
            //Do whatever you want with filename and its binaray data.
        }
        return Json (new { Message = "Hooray!" });
    }

...and here's what VS2015 makes of it:

VS2015 issues

With DNXcore5.0 it seems that MultipartMemoryStreamProvider which is part of System.Net.Http can't be found in the namespace, and Request.Body doesn't work with ReadAsMultipartAsync (which couldn't be found anyway, because it's in that System.Net.Http space...)

Is there a better way to set up an API POST to accept files in ASP.NET 5? Or how do we now reference things like System.Net.Http that have worked for years?

I am beginner in ASP.NET and after lot of searching I've decided to ask you guys.

So, I have object created in embedded block in my Page.aspx in following way:

<% Invoice invoice = InvoiceGateway.get(1); %>

Implementation of these is in different files Invoice.cs and InvoiceGateway.cs I am using it to fill webelements right where I need it in this way:

<p class="list-group-item-text"><%= invoice.getCreator().getAddress() %></p>

But now I've started to create buttons and I am trying to call method of this object when I click the button e.g.

<a class="btn btn-danger" runat="server" onServerClick="<% invoice.delete() %>">
     delete
</a>

I know this is not correct, its just for illustration of what I am trying to achieve.

I am not sure how (or even if) I can do that. I know I can define some function in .aspx.cs page and call it onServerClick, or just redirect to Page.aspx?delete={id} and perform something on load.

My question is... Is there a way how to call method of such created object, after I click some hyperlink/button/etc? I've come up with some alternatives, but nothing that would use this already created object and its method.

As said in many tutorials I added a ViewImport.cshtml file. To this file I added the following code:

@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers" And inside of the project.json I added the following two lines:

"Microsoft.AspNet.Tooling.Razor": "1.0.0-beta4" "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta7"

This is what every tutorial tells me to do, but I still get a white browser screen. I am very frustrated with this and don't know what I can do more. Thanks if someone can help me!

I have tried creating an ASP.NET MVC application which works perfectly when "locally" deployed, I want to deploy to an online web hosting company. I am beset by errors like trust level not right (tried to set it in web.config but the hosting company doesn't allow changing that, so how to specify it?) - tried creating a basic "empty" web site with no database access, file system access etc but just a static html page and I get "don't know what ASP.NET web pages version to use"

What do I need to look for in a suitable web host to be able to create a simple web application and deploy it to my domain - Seems like it should be a simple task but I am totally frustrated by silly issues.

The easy part is actually writing the code - the hard part seems to be deploying and running the wretched thing!!!

I found this code, I want to convert this Razor code to aspx view engine, also please explain to me the purpose from this code.

<script>
$(document).ready(function(){
$("#btn-register").click(function () {
    var posting = $.post("api/Register",
        $("#saveContactForm").serialize(),
        function(value) {
            console.log(value);
        },
        "json"
    ).complete(function (data) {
        alert(data.responseText);
    });
    return false;
});

});