I have 3 tier web site asp.net c#. I want to select user and check his user-type for login.but my code not work. and above error shown. pleas help me what do I do. my code DAL:

public SqlDataReader select_user(string UserName)
        {
            connect.Open();
            SqlCommand cmd = new SqlCommand("SELECT * FROM UserInfo WHERE UserName=@UserName", connect);
            cmd.Parameters.AddWithValue("@UserName", UserName);
            SqlDataReader dr = cmd.ExecuteReader();
            return dr;
        }

and BL:

 public SqlDataReader Get_user()
        {
            return da.select_user(UserName);
        }

and code of interface:

 try
        {

            bll.UserName = UserNameTextBox.Text;
            Session.Add("_UserName", bll.UserName);
            bll.Get_user();
            SqlDataReader dr = bll.Get_user();
            if (dr.HasRows)
            {
                dr.Read();
                int Utyp = bll.UserTyp;
                if (Utyp == 0)
                {
                    Session.Add("Msg_", "dear user. you are unactive yet");
                    Response.Redirect("ShowMessage.aspx", false);
                }
                else
                    if (Utyp == 1)
                    {
                        Response.Redirect("index.aspx", false);
                    }

            }
            else
            {

            }
        }
         catch (Exception ex)
         {
             Session.Add("Msg_", "  : <br>" + ex.Message);
             Response.Redirect("~/ShowMessage.aspx");
         }

I am trying to block spam messages where spammers are sending the same message but from multiple IP addresses, can you kindly suggest how would that be prevented?

The technologies I'm using are: Asp.Net MVC, MSSQL, Redis Cache

Thank you very much

I am currently working on two web applications which are hosted on two separate local servers which are distinguished by their port numbers in Asp.Net I want to post data from server1 to server2. Apart from using QueryString, what is the best way to do this?

Note: The applications are separate.. That is in different projects under one solution

I have an oldish asp.net website I've been slowly refactoring to use angularjs. One of my pages calls a very long running process that I want to keep the user informed about progress, and also to keep their session active.

I thought I could achieve this by using some angularjs such as the following:

    $scope.setupLongRunningProcess= function() {
        $scope.progress = {};
        $scope.result = null;

        startLongRunningProcess();

        $timeout(function () {
            pollProgress();
        }, 5000);
    }

   function pollProgress() {
        if (!$scope.result) {
            $http({
                method: "POST",
                url: "MyPage.aspx/PollProgressJson",
                data: {}
            }).then(function successCallback(response) {
                $scope.progress.Count = response.data.d;

                $timeout(function() {
                        pollProgress();
                }, 5000);
            });
        }
    }

    function startLongRunningProcess() {
        $http({
            method: "POST",
            url: "MyPage.aspx/LongRunningProcessJson",
            data: {}
        }).then(function successCallback(response) {
            $scope.result = response.data.d;
        });
    }

It starts out OK, calling startLongRunningProcess() which calls MyPage.aspx/LongRunningProcessJson, and then calls pollProgress() as expected. However, it never gets to MyPage.aspx/PollProgressJson on the server. The long running processs on the server is just a usual WebMethod:

<WebMethod>
Public Shared Function LongRunningProcessJson(...) As Result(Of String)
    Dim service As LongRunningProcessService = GetService...
    Return service.LongRunningProcess(..., HttpContext.Current.Session)
End Function

Here I was using the Http Session to put in a count of progress, and all PollProgressJson is doing is querying that.

I didn't want my original call to LongRunningProcessJson to finish until it is complete, so should I be making an async call in there to do all the work (and wait until it is finished before returning)?

Or, am I taking completely the wrong approach? (and yes, I know, I don't like passing in a Session object to my business layer, it does feel very icky)

I've been spending my time building a site with Umbraco and I'm almost done except I can't get the HttpPost for my Contact View to work. As I get the following error: enter image description here

I've tried quite a few things I found around here and on Umbraco Forums but nothing has been useful so far, at first I thought it was the validation itself so I changed that and even changed the AJAX action but nothing worked, after debugging I found this error but I have no idea how to approach a solution.

This is the entire controller code:

  public class ContactSurfaceController : SurfaceController
    {
        public ActionResult Index()
        {
            return PartialView("ContactView", new ContactViewModel());
        }

        [HttpPost]
        [NotChildAction]
        public ActionResult Submit(ContactViewModel form)
        {

            if (!ModelState.IsValid)
            {
                return Json(new { Success = false });
            }

            SectionContact currSection = (SectionContact)Umbraco.TypedContent(form.CurrentSectionId);

            string mailTo = currSection.AdministratorsEmail;
            string mailFrom = currSection.NotificationMailFrom;
            string mailFromAlias = currSection.NotificationMailSenderAlias;
            string message = string.Concat(currSection.NotificationEmailBody, "<br/><br/>", umbraco.library.StripHtml(form.Message));

            //Use predefined subject. If predefined subject is not defined, use current subject from form (if any)
            string subject = (string.IsNullOrEmpty(currSection.NotificationEmailSubject)) ? form.Subject : currSection.NotificationEmailSubject;

            //If all else fails, use standard subject from dictionary.
            subject = (string.IsNullOrEmpty(subject)) ? Umbraco.GetDictionaryValue("ContactForm.Subject") : subject;

            StringBuilder sb = new StringBuilder(string.Empty);

            if (!string.IsNullOrEmpty(form.Name))
            {
                sb.Append("Name:");
                sb.Append("<br/>");
                sb.Append(form.Name);
                sb.Append("<br/><br/>");
            }

            if (!string.IsNullOrEmpty(form.Subject))
            {
                sb.Append("Subject:");
                sb.Append("<br/>");
                sb.Append(form.Subject);
                sb.Append("<br/><br/>");
            }

            sb.Append("Email: ");
            sb.Append("<br/>");
            sb.Append(form.Email);
            sb.Append("<br/><br/>");

            sb.Append("Message: ");
            sb.Append("<br/>");
            sb.Append(umbraco.library.ReplaceLineBreaks(message));
            sb.Append("<br/><br/>");

            if (!string.IsNullOrEmpty(currSection.Dropdown1Values))
            {
                sb.Append(currSection.Dropdown1Values.Split(new string[] { "\n", "\n\r" }, StringSplitOptions.RemoveEmptyEntries)[0]);
                sb.Append("<br/>");
                sb.Append(form.DropDown1);
                sb.Append("<br/><br/>");
            }

            if (!string.IsNullOrEmpty(currSection.Dropdown2Values))
            {
                sb.Append(currSection.Dropdown2Values.Split(new string[] { "\n", "\n\r" }, StringSplitOptions.RemoveEmptyEntries)[0]);
                sb.Append("<br/>");
                sb.Append(form.DropDown2);
                sb.Append("<br/><br/>");
            }

            if (ModelState.IsValid)
            {
                Utils.SendEmail(mailFrom, mailFromAlias, mailTo, subject, sb.ToString());
            }

            return Json(new { Success = true });
        }


    }

Here is the partial view:

@inherits Umbraco.Web.Mvc.UmbracoViewPage<SectionContact>

@using DotSee.Models;
@using DotSee.UmbracoExtensions;

@{

    SectionContact currSection = Model;
    int currSectionId = currSection.Id;

    string[] dropDown1Data = currSection.Dropdown1Values.Split(new string[] { "\n", "\n\r" }, StringSplitOptions.RemoveEmptyEntries);
    string[] dropDown2Data = currSection.Dropdown2Values.Split(new string[] { "\n", "\n\r" }, StringSplitOptions.RemoveEmptyEntries);

}

<section id="contactForm_@currSectionId" class="@currSection.GetSectionEffectCssClass() ptb-60 ptb-sm-60">
    <div class="container">

        @if (!string.IsNullOrEmpty(currSection.IntroText) || !currSection.HideTitle)
        {

            <div class="row">
                <div class="col-md-6 col-md-offset-3 text-center">

                    @if (!currSection.HideTitle)
                    {
                        <h3>@currSection.Name</h3>
                    }

                    @if (!string.IsNullOrEmpty(currSection.IntroText))
                    {
                        <p class="lead">@currSection.IntroText</p>
                    }

                </div>
            </div>
            <div class="spacer-15"></div>
        }

        @Html.Partial("ContactView", new ContactViewModel()
                   , new ViewDataDictionary
                   {
                         { "currSectionId", currSection.Id }
                       , { "hideSubject", currSection.HideSubject }
                       , { "hideName", currSection.HideName }
                       , { "dropDown1Data", dropDown1Data }
                       , { "dropDown2Data", dropDown2Data }
                   })
        </div>
</section>

And finally this is the view contact view:

@inherits Umbraco.Web.Mvc.UmbracoViewPage<ContactViewModel>
@using DotSee.UmbracoExtensions
@using DotSee.Models
@using DotSee.Controllers
@using Umbraco.Web
@using ClientDependency.Core.Mvc;

@{
    Html.RequiresJs("/scripts/jquery.unobtrusive-ajax.min.js",9999);
    Html.RequiresJs("/scripts/jquery.validate.min.js", 9999);
    Html.RequiresJs("/scripts/jquery.validate.unobtrusive.min.js", 9999);

    int currSectionId = Convert.ToInt32(ViewData["currSectionId"]);
    bool hideSubject = (bool)ViewData["hideSubject"];
    bool hideName = (bool)ViewData["hideName"];
    string[] dropDown1Data = (ViewData["dropDown1Data"] as string[]);
    string[] dropDown2Data = (ViewData["dropDown2Data"] as string[]);
}


        <div class="row">
            <div id="contactFormMessages" class="ptb-0 col-md-6 col-md-offset-3 text-center">

                <h6 id="contactSuccess" class="successContent">
                    <i class="fa fa-check left" style="color: #5cb45d;"></i>@Umbraco.GetDictionaryValue("ContactForm.Success")
                </h6>

                <h6 class="errorContent">
                    <i class="fa fa-exclamation-circle left" style="color: #e1534f;"></i>@Umbraco.GetDictionaryValue("ContactForm.Failure")
                </h6>

               </div>

            <div id="contactFormHolder" class="col-md-6 col-md-offset-3">
                @using (Ajax.BeginForm("Submit", "ContactSurface", new AjaxOptions
                {
                    HttpMethod = "POST",
                    OnFailure = "ShowContactError",
                    OnSuccess = "ShowContactSuccess",
                }))
                {

                    @Html.TextBoxFor(model => model.CurrentSectionId, new { Value = Convert.ToInt32(currSectionId) })
                    if (!hideName)
                    {
                        <div class="form-field-wrapper">
                            @Html.TextBoxFor(model => model.Name, new { @Placeholder = "Name", @class = "input-sm form-full" })
                        </div>
                    }
                    <div class="form-field-wrapper">
                        @Html.TextBoxFor(model => model.Email, new { @Placeholder = "Email", @class = "input-sm form-full" })
                        @Html.ValidationMessageFor(model => model.Email, Umbraco.GetDictionaryValue("ContactForm.Email.Invalid"))
                    </div>
                    if (!hideSubject)
                    {
                        <div class="form-field-wrapper">
                            @Html.TextBoxFor(model => model.Subject, new { @Placeholder = "Subject", @class = "input-sm form-full" })
                        </div>
                    }
                    <div class="form-field-wrapper">
                        @Html.TextAreaFor(model => model.Message, new { @Placeholder = "Content", @class = "form-full", @rows = 7 })
                        @Html.ValidationMessageFor(model => model.Message, Umbraco.GetDictionaryValue("ContactForm.Message.Required"))
                    </div>
                    if (dropDown1Data != null && dropDown1Data.Length > 1)
                    {
                        @Html.DropDownListFor(model => model.DropDown1, dropDown1Data.Select(f => new SelectListItem { Value = f, Text = f }).Skip(1), dropDown1Data[0], new { @class = "form-full" })
                    }
                    if (dropDown2Data != null && dropDown2Data.Length > 1)
                    {
                        @Html.DropDownListFor(model => model.DropDown2, dropDown2Data.Select(f => new SelectListItem { Value = f, Text = f }).Skip(1), dropDown2Data[0], new { @class = "form-full" })
                    }
                    <button class="btn btn-md btn-black form-full" type="submit" id="form-submit" name="submit">@Umbraco.GetDictionaryValue("ContactForm.Submit")</button>
                }
            </div>
        </div>

<script type="text/javascript">

    function ShowContactError() {
         $(".errorContent").show();
            $("#contactFormHolder").hide();
    }

    function ShowContactSuccess(arg) {
        if (arg.Success === true) {
            $("#contactSuccess").show();
            $("#contactFormHolder").hide();
        }
        else
        {
            $(".successContent").show();
            $("#contactFormHolder").hide();

        }
    }

</script>

I want my ApplicationContext constructor to have the UserManager as a parameter but having trouble with dependency injection.

Code:

public class ApplicationContext : IdentityDbContext<ApplicationUser>
    {
        private IHttpContextAccessor _contextAccessor { get; set; }
        public ApplicationUser ApplicationUser { get; set; }
        private UserManager<ApplicationUser> _userManager;

        public ApplicationContext(DbContextOptions<ApplicationContext> options, IHttpContextAccessor contextAccessor, UserManager<ApplicationUser> userManager)
            : base(options)
        {
            _contextAccessor = contextAccessor;
            var user = _contextAccessor.HttpContext.User;
            _userManager = userManager;
            ApplicationUser = _userManager.Users.FirstOrDefault(u => u.Id == _userManager.GetUserId(user));
        }
}

And in startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddDbContext<ApplicationContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("RCI.App")));

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

            services.AddAuthentication();

            services.AddMvc();

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();
            services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();

            services.AddOptions();

        }

Error code:

A circular dependency was detected for the service of type 'Microsoft.AspNetCore.Identity.UserManager`1[RCI.App.Models.ApplicationUser]'.

Could anyone point out what I'm doing wrong?

The generation of automatic scaffold to Asp.Net Razor Page is compatible to bool data types?

I ask about it, because I'm following this tutorial: https://docs.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/model. And at a point, after create the POCO class, configure dbContext and migrations, I ran this command to automatic generate the scaffold

dotnet aspnet-codegenerator razorpage -m Movie -dc MovieContext -udl -outDir Pages\Movies --referenceScriptLibraries

Its beautiful, but just working if my POCO class hasn't a bool type.

Example POCO class:

using System;

namespace RazorPagesMovie.Models
{
    public class Movie
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public DateTime ReleaseDate { get; set; }
        public string Genre { get; set; }
        public bool Active { get; set; }
    }
}

With this implementation I'll get, when try to Create a Movie, this error:

'CreateModel' does not contain a definition for 'Active' and no extension method 'Active' accepting a first argument of type 'CreateModel' could be found (are you missing a using directive or an assembly reference?)

Any idea?

Maybe is a necessary information the fact of I'm using SQLite as Database...

And the CreateModel class:

using System;    
using System.Collections.Generic;    
using System.Linq;    
using System.Threading.Tasks;    
using Microsoft.AspNetCore.Mvc;    
using Microsoft.AspNetCore.Mvc.RazorPages;    
using Microsoft.AspNetCore.Mvc.Rendering;    
using RazorPagesMovie.Models;

namespace RazorPagesMovie.Pages.Movies    
{    
    public class CreateModel : PageModel    
    {    
        private readonly RazorPagesMovie.Models.MovieContext _context;    

        public CreateModel(RazorPagesMovie.Models.MovieContext context)    
        {    
            _context = context;    
        }        

        public IActionResult OnGet()    
        {    
            Movie = new Movie    
            {    
                Title = "The Good, the bad, and the ugly",    
                Genre = "Western",    
                Price = 1.19M,    
                ReleaseDate = DateTime.Now,    
                Active = true    
            };    
            return Page();    
        }        

        [BindProperty]    
        public Movie Movie { get; set; }    

        public async Task<IActionResult> OnPostAsync()    
        {    
            if (!ModelState.IsValid)    
            {    
                return Page();    
            }    

            _context.Movie.Add(Movie);    
            await _context.SaveChangesAsync();    

            return RedirectToPage("./Index");    
        }    
    }    
}

I need to set the Font.Size property in Points. So normally I could set font-size:12pt in markup, but I need to switch the font size from the server side in code behind.

I set the lblText.Font.Size = 12 but the text is too small. What unit of measurement is used by default and how to convert it to points?

This is for a web application that has a C# back-end. The way it is architected I am not able to just import one of these classes to the other to call the method directly. Unfortunately, we have something going wrong with our build process, so I am unable to debug this code, so I'm hoping to nail it in as few iterations as possible.

In one controller we have this method:

    [Route("api/uploadFile/{id}")]
    [HttpPost]
    [CustomAuthorize]
    [SwaggerResponse(HttpStatusCode.OK, Description = "File upload successful")]
    [SwaggerResponse(HttpStatusCode.InternalServerError, "Error uploading file")]
    public async Task<IHttpActionResult> PostFile(int id, [FromUri]bool replace=false)
    {
        //code to put the file in the database;
    }

and I need to figure out how to call that from a different controller. These two controllers are in two completely separate projects and have no knowledge of each other.

I've tried a handful of variations of the following, but it each change takes about 8 mins in a build process so I didn't want to just hack on it anymore:

    HttpClient htc = new HttpClient();
    HttpContent content = new StreamContent(myfile);
    var response = await htc.PostAsync(this.Url.Content("~/api/uploadFile/9992"),  content);
    var responseString = await response.Content.ReadAsStringAsync();

I have a dropdown and some other fields in my view. i want to populate the model through ajax call in Edit Mode.my problem is that when i click on edit button all the other field populate with there respective data, but the dropdown does not populate with the selected value (the value that comes in json respone from controller to the view through ajax call).


My View is the following:

ARF.UI.Areas.MVC.Models.CarawayEntities entities = new 
    ARF.UI.Areas.MVC.Models.CarawayEntities();

var FgsProducts = new SelectList(entities.Sales_GetFGSProducts(), "ItemId", "Name");
ViewBag.ProductId = FgsProducts;

<div id="content">
    <div class="container">

        <div class="box effect7 col-md-12">
            <input type="hidden" id="aaa" />
            <div class="col-md-12">
                <div class="col-md-12"><h1 class="login headerCss">Sales Target</h1></div>
                <hr />
                @using (Html.BeginForm())
                {
                    @Html.AntiForgeryToken()
                    <div class="form-horizontal">
                        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                        <div class="row">

                            <div class="col-md-12 borderDiv">
                                <div class="col-md-2"><label>ROI#:</label></div>
                                <div class="col-md-4">
                                    @Html.EditorFor(model => model.ROIId, new { htmlAttributes = new { @class = "form-control", @Value = ViewBag.Id, id = "RoiId", @readonly = "readonly", } })
                                </div>
                            </div>
                        </div>
                        <br />
                        <div class="row">

                            <div class="col-md-12 borderDiv">
                                <div class="col-md-2"><label>Brand Name:</label></div>
                                <div class="col-md-4">
                                    @Html.DropDownListFor(model => model.ProductId, new SelectList(ViewBag.ProductId, "Value", "Text"), new { @class = "form-control simple-select", required = "required" })
                                    @Html.ValidationMessage("ProductId", "", new { @class = "text-danger" })
                                </div>
                                <div class="col-md-2"><label>PackSize:</label></div>
                                <div class="col-md-4">
                                    @Html.DropDownListFor(model => model.PackSizeId, new SelectList(Enumerable.Empty<SelectListItem>(), "PackSizeId", "Name"), new { @class = "form-control simple-select", required = "required" })
                                    @Html.ValidationMessageFor(m => m.PackSizeId, "", new { @class = "text-danger" })
                                </div>

                            </div>
                        </div>
                        <br />
                        <div class="row">
                            <div class="col-md-12 borderDiv">
                                <div class="col-md-2"><label>Month1:</label></div>
                                <div class="col-md-4">
                                    @Html.EditorFor(model => model.Month1, new { htmlAttributes = new { @class = "form-control" } })
                                    @Html.ValidationMessageFor(m => m.Month1, "", new { @class = "text-danger" })
                                </div>
                                <div class="col-md-2"><label>Month2:</label></div>
                                <div class="col-md-4">
                                    @Html.EditorFor(model => model.Month2, new { htmlAttributes = new { @class = "form-control" } })
                                    @Html.ValidationMessageFor(m => m.Month2, "", new { @class = "text-danger" })
                                </div>
                                <input type="hidden" id="SaleTargetId" />

                            </div>
                        </div>
                        <br />


                        <br />
                        <div class="row">
                            <div class="form-group">
                                <div class="col-md-offset-2 col-md-10">
                                    <button type="button" class="btn btn-default" id="btnAdd" onclick="GetSaleTargetEdit()" style="margin-left:1%">Edit</button>

                                </div>
                            </div>
                        </div>
                    </div>
                    <br />
                }
            </div>
        </div>
    </div>
</div>

Now when i click on the Edit Button. The Following Javascript Funtion is Called.

function GetSaleTargetEdit(obj) {
            $.ajax({
                url: '/MVC/Sales_ROI/GetSaleTargetDetail',
                type: 'POST',
                data: '{id: ' + obj + ' }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (s) {
                    var Message = s.MessageCode;
                    if (Message == '1') {

                        $('#ProductId').val(s.ProductId);

                        $('#PackSizeId').val(s.PackSizeId);
                        $('#Month1').val(s.Month1);
                        $('#Month2').val(s.Month2);

                    }


                }, error: function (e) { console.log(e.responseText); }
            });
        }

In Start i am loading the Product dropdown from the viewbag.ProductId as i mentiond its code in the start of my view. I save its value to the database for first time entry but the problem occurs when i am editing the model.

The above Function correctly Load data from the Controller Method. and fill all the other fields with respective data, but only the dropdown for Product ie (ProductId) which is the id of the dropdown for products, not become selected bases on this value. Please Help me.

In my ASP.NET MVC (6) web Web Api I have

[Produces("application/json")]
[Route("api/Record")]
public class RecordController : Controller
{

    // ...

    // GET: api/Record/5
    [HttpGet("{id}", Name = "GetRecord")]
    public async Task<Record> Get(string id)
    {
        var record = await repository.GetAsync<Record>(id);            
        return record;
    }

Now, my Record contains some Tags.

I would like to return these tags via api/Record/5/Tags

How should I write my action in that case?

The generation of automatic scaffold to Asp.Net Razor Page is compatible to bool data types?

I ask about it, because I'm following this tutorial: https://docs.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/model. And at a point, after create the POCO class, configure dbContext and migrations, I ran this command to automatic generate the scaffold

dotnet aspnet-codegenerator razorpage -m Movie -dc MovieContext -udl -outDir Pages\Movies --referenceScriptLibraries

Its beautiful, but just working if my POCO class hasn't a bool type.

Example POCO class:

using System;

namespace RazorPagesMovie.Models
{
    public class Movie
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public DateTime ReleaseDate { get; set; }
        public string Genre { get; set; }
        public bool Active { get; set; }
    }
}

With this implementation I'll get, when try to Create a Movie, this error:

'CreateModel' does not contain a definition for 'Active' and no extension method 'Active' accepting a first argument of type 'CreateModel' could be found (are you missing a using directive or an assembly reference?)

Any idea?

Maybe is a necessary information the fact of I'm using SQLite as Database...

And the CreateModel class:

using System;    
using System.Collections.Generic;    
using System.Linq;    
using System.Threading.Tasks;    
using Microsoft.AspNetCore.Mvc;    
using Microsoft.AspNetCore.Mvc.RazorPages;    
using Microsoft.AspNetCore.Mvc.Rendering;    
using RazorPagesMovie.Models;

namespace RazorPagesMovie.Pages.Movies    
{    
    public class CreateModel : PageModel    
    {    
        private readonly RazorPagesMovie.Models.MovieContext _context;    

        public CreateModel(RazorPagesMovie.Models.MovieContext context)    
        {    
            _context = context;    
        }        

        public IActionResult OnGet()    
        {    
            Movie = new Movie    
            {    
                Title = "The Good, the bad, and the ugly",    
                Genre = "Western",    
                Price = 1.19M,    
                ReleaseDate = DateTime.Now,    
                Active = true    
            };    
            return Page();    
        }        

        [BindProperty]    
        public Movie Movie { get; set; }    

        public async Task<IActionResult> OnPostAsync()    
        {    
            if (!ModelState.IsValid)    
            {    
                return Page();    
            }    

            _context.Movie.Add(Movie);    
            await _context.SaveChangesAsync();    

            return RedirectToPage("./Index");    
        }    
    }    
}

Hi I am unable to access my Web Project deployed at IIS. The project is .net based mvc application. I have deployed it 6 months ago at a machine and it worked fine but now if I access it after deployment error is : "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable." attached in image.ERROR's

I have seen multiple blogs / answers and unable to get it done. IIS is 7.0 framework is 4.0 Integrated Pipeline mode and deployed website has static handler mappings set to '*' as well. ( stuff i got from other stack answers)

Please advise i am sure its not web config or code related problem and due to iis or something.

I think the [Phone] annotation should be applying a standard regex pattern to the UI input field but I am finding that I can enter anything words, all manner of special characters and no validation errors occur.

Below is the HTML and then Model entry

<div class="form-group">
  <label class="col-sm-3 control-label">@Html.DisplayNameFor(m => m.Supplier.Phone)</label>
  <div class="col-sm-9">
    @Html.TextBoxFor(m => m.Supplier.Phone, new { @class = "form-control", id = "Phone" })
    <span asp-validation-for="Supplier.Phone" class="text-danger"></span>
   </div>
 </div>

[Required]
[Phone]
public string Phone { get; set; }

All other validations such as [EmailAddress], [Range] and [Required] are working just fine.

I did come across this stackoverflow article suggesting the HTML5 did not support phone, is that still correct?

I am writing simple consoleApp (netcoreapp2.0)

<Project Sdk="Microsoft.NET.Sdk">

and want to run webserver with mvc.

class Program
{
    static void Main(string[] args)
    {
        WebHost.CreateDefaultBuilder()
            .ConfigureServices(services => services.AddMvc())
            .Configure(app => app.UseDeveloperExceptionPage().UseMvcWithDefaultRoute())
            .UseHttpSys().Build().Run();
    }
}

public class HomeController : Controller
{
    [HttpGet] public ActionResult Index() => View("Index");
}

I get an error while GET http//localhost:5000

One or more compilation references are missing. Ensure that your project is referencing 'Microsoft.NET.Sdk.Web' and the 'PreserveCompilationContext' property is not set to false.

Probably reason is in Razor Engine. How can i make it work? What did i miss?

In razor view I use Html.EditFor.

@Html.EditorFor(model => model.Salary, new { htmlAttributes = new { id = "SalaryEdit", @class = "form-control", onkeypress = "myFunction()" } })

Script

 function myFunction() {
                var source = $('#SalaryEdit');
                console.log($("input[id^='SalaryEdit']").val());
            }

When I type in EditorFor for example: 1,23. It shows me only 1,2. It always cut last char. What is the reason?

I want to develop new website like stackoverflow as well as quora.com. But I am not getting some point that how to dynamically generate new page with action method and controller with the help of ASP MVC.

e.g.,

Question -> What is MVC ?

So, when question is post, that time in root folder it is dynamically generate new MVC for that question.

I am using an autocomplete extender on my asp.net webpage to fetch data when a user starts typing a last name. Only when it seems there are a ton of results being returned, it never lets the user select an item from the drop down. It searches for a last name by state so if a user types in a 2 letter last name such as "Li" there could be many results returned from this. Is there a way to allow more results without it autoclosing?

      <asp:AutoCompleteExtender ID="AutoCompleteExtender" runat="server" 
    DelimiterCharacters="" Enabled="True" ServicePath="AutoComplete.asmx" 
            ServiceMethod="GetCompletionList" TargetControlID="NameTextBox" 
            UseContextKey="true" ContextKey="StateDropDown" 
            onclientitemselected="getSelected"
            ShowOnlyCurrentWordInCompletionListItem="True" CompletionInterval="100" 
            MinimumPrefixLength="2" CompletionListElementID="autocompleteDropDownPanel"
               CompletionListCssClass="style101" OnClientShown="checkFocusOnExtender">

        </asp:AutoCompleteExtender>

I have an ASP.Net web form with a drop down list and two jQuery date pickers(Start Date and End Date). I need to be able to:

clear and disable both date pickers if DDL value is -1; set End Date date to Start Date date and disable End Date calendar if DDL value is 1 and enable both calendars and set their dates to today's date otherwise.

Below is what I have so far. It disables end date if selected value is 1 but if I change the selected value and then select 1 again, it won't disable and selected date in it disappears. I use a client side onchange for drop down list.

<div class="col-sm-2 col-md-2">
    <div class="form-group"><label>Frequency</label><br />
        <asp:DropDownList runat="server"
            ID="ddlFrequency" 
            CssClass="form-control" 
            DataSourceID="odsFrequency" 
            DataTextField="Frequency" 
            DataValueField="FrequencyID" 
            AppendDataBoundItems="true" 
            onchange="freqChanged(this)">
            <asp:ListItem Text="Select Frequency" Value="0" />
        </asp:DropDownList>
    </div>
</div>

<div class="col-sm-3 col-md-3">
    <div class="form-group"><label>Start Date</label><br />
        <div class="input-group input-append date" id="tpStartDate">
            <input runat="server" id="tbStartDate" clientidmode="static" type="text" class="form-control" style="width:85%" /> 
        </div>
    </div>
</div>
<div class="col-sm-3 col-md-3">
    <div class="form-group"><label>End Date</label><br />
        <div class="input-group input-append date" id="tpEndDate">
            <input runat="server" id="tbEndDate" clientidmode="static" type="text" class="form-control test" style="width:85%" />
        </div>
    </div>
</div>

function pageLoad() {
    $('#tbStartDate').unbind();
    $("#tbStartDate").datepicker({
        showOtherMonths: true,
        selectOtherMonths: true,
        showOn: "button",
        buttonImage: "../assets/images/calendar.gif",
        buttonImageOnly: true,
        buttonText: "Select Statrt Date",
        option: "mm/dd/yy",
        onSelect: function (dateStr) {
            var freq = $('#<%= ddlFrequency.ClientID %>').val();
            $("#tbEndDate").val(dateStr);
            $("#tbEndDate").datepicker("option", { minDate: new Date(dateStr) })

        if (1 == freq) {
            $("#tbEndDate").datepicker('disable');
        }
        else {
            $("#tbEndDate").datepicker('enable');
        }
    }
});
$('#tbEndDate').unbind();
    $("#tbEndDate").datepicker({
        showOtherMonths: true,
        selectOtherMonths: true,
        showOn: "button",
        buttonImage: "../assets/images/calendar.gif",
        buttonImageOnly: true,
        buttonText: "Select End Date",
        option: "mm/dd/yy"
    });
}

function freqChanged(ddl) {
    var freq = ddl.value;
    if (freq == 1) {
        startDate = $("tbStartDate").datepicker('getDate');
        $("#tbEndDate").val(startDate);
        $("#tbEndDate").datepicker("option", { minDate: new Date(startDate) });
        $('#tbEndDate').datepicker('disable');
    }
    else {
        $("#tbEndDate").datepicker('enable');
    }
}

In my search for a way to send email on my webapp through a form, the only solution I got working was an old MSDN solution for a WebMail helper where it had me hardcode the credentials for an email to send through.

Right, off the bat, I know this is not ideal. Is there an easy way to send this mail out from a WebMail default so I can remove the login credentials and not look so amateurish???

@{
var customerName = Request["customerName"];
var customerEmail = Request["customerEmail"];
var customerPhone = Request["customerPhone"];
var customerRequest = Request["customerRequest"];
var errorMessage = "";
var toMail = "user@mail.com";
var debuggingFlag = false;
try
{
    // Initialize WebMail helper
    WebMail.SmtpServer = "smtp.gmail.com";
    WebMail.SmtpPort = 587;
    WebMail.UserName = "user@mail.com";
    WebMail.Password = "Password!";
    WebMail.From = "user@mail.com";
    WebMail.EnableSsl = true;

    // Send email
    WebMail.Send(to: toMail,
        subject: "Quote/Info request from - " + customerName,
        body: customerPhone + customerRequest
    );
}
catch (Exception ex)
{
    errorMessage = ex.Message;
}

I installed IIS on window 10. then i sopped it also from control panel i turned it off. but local-host still working. why? Please help