I am using Razor MVC 5. I have code that works in a controller. It uses AE.Net.Mail and I have run Install-Package AE.Net.Mail with nuget console, although I suspect that's not terribly relevant to my issue.

Project/Controllers/TestController.cs

using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using WebFloV2.Data;
using System;
using AE.Net.Mail;

namespace Something.Controllers
{
    public class TestController : DataController
    {        
        public ActionResult DoStuff()
        {
            ImapClient ic = new ImapClient("imap.gmail.com", "example@gmail.com", "password", AuthMethods.Login, 993, true);
            ic.SelectMailbox("INBOX");
        }
    }
}

This works, but I wanted to move this logic into a new folder called Libraries. I have added <Compile Include="Libraries\Test.cs" /> to .csproj. Here is the new path and code.

Project/Libraries/Test.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AE.Net.Mail;

namespace WebFloV2.Libraries
{
    public class ShippingExceptions
    {
            ImapClient ic = new ImapClient("imap.gmail.com", "example@gmail.com", "password", AuthMethods.Login, 993, true);
            ic.SelectMailbox("INBOX");
    }
}

In this new file location, I hit an issue. On ic.SelectMailbox("INBOX"); I get

The name 'ic' does not exist in the current context.

This is strange to me, because it worked as Controller logic and there's no issues with the previous line ImapClient ic = ... where I define it. If I must, I could use the controller, but I'd like to know if what I'm attempting is possible.

How can I use ic in Project/Libraries/Test.cs?

I have two entities in my database:Patient and Doctor, which contains one-to-many relationship.Classes are as follows:

public partial class Doctor
{
    public Doctor()
    {
        this.Patients = new HashSet<Patient>();
    }
    public int DoctorID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Country { get; set; }
    public System.DateTime Birthday { get; set; }
    public byte[] Photo { get; set; }
    public string Password { get; set; }
    public string PasswordSalt { get; set; }
    public int SpecialityID { get; set; }

    public virtual Speciality Speciality { get; set; }
    public virtual ICollection<Patient> Patients { get; set; }
}



public partial class Patient
{
    public int PatientID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Gender { get; set; }
    public string MaritalStatus { get; set; }
    public System.DateTime Birthday { get; set; }
    public string Phone { get; set; }
    public int DoctorID { get; set; }
    public System.DateTime EntryDate { get; set; }

    public virtual Doctor Doctor { get; set; }
    public virtual PatientAddress PatientAddress { get; set; }
}

This is code for adding a patient to a doctor.

public ActionResult AddPatient(PatientViewModel patientVM)
    {
        using (PeopleCareEntities PeopleEntities=new PeopleCareEntities())
        {
            PatientAddress patientAddress = Mapper.Map<PatientViewModel, PatientAddress>(patientVM);
            Patient patient = Mapper.Map<PatientViewModel, Patient>(patientVM);
            int currentDoctor = ((Doctor)Session["Doctor"]).DoctorID;
            //problem is here
            Doctor doctor=PeopleEntities.Doctors.Single(a=>a.DoctorID==currentDoctor);
            var doctorPatients = doctor.Patients.FirstOrDefault(a=>a.Email==patientVM.Email);
            if (doctorPatients==null)
            {
                patient.EntryDate = DateTime.Now;
                patient.DoctorID = doctor.DoctorID;
                doctor.Patients.Add(patient);
                PeopleEntities.SaveChanges();
                patientAddress.PatientID = patient.PatientID;
                PeopleEntities.PatientAddresses.Add(patientAddress);
                PeopleEntities.SaveChanges();
                return Json(new { Message = "Patient added successfully !" }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { Message="Patient already exist !" }, JsonRequestBehavior.AllowGet);
            }
        }
    }

Adding a patient in database works perfectly,but doctor.Patients has always Count=0. in debug mode. Thanks in advance.

In my application i have an Index method that generates a view based on a viewmodel.

Now i have a second method which does almost exactly the same but adds a filter to this.

    [Menu("Active messages")]
    public async Task<ActionResult> Index(int? pageNumber)
    {
        var vm = await mediator.Send(new ActiveMessagesViewModelQuery());
        var index = await mediator.Send(new MessageLogQuery());

        vm.MessageLogList = index.ToPagedList(pageNumber ?? 1, pageSize);
        return View(vm);
    }

    [HttpPost]
    public async Task<ActionResult> Filter(List<int> locations, List<int> machines, List<int> severities, List<int> messages)
    {
        var vm = await mediator.Send(new ActiveMessagesViewModelQuery());
        var filteredmessages = await mediator.Send(new MessageLogQuery
        {
            Filter = new MessageLogFilter
            {
                SelectedMessages = messages
            }
        });

        vm.MessageLogList = filteredmessages.ToPagedList(1, pageSize);
        vm.SelectedMessages = messages;

        return View(nameof(Index), vm);
    }

the vm type that is added is in both instances the same type. When i call the filter method nothing changes in the current view, i keep the same data. i've already checked and the data i send in the filter method is correct so i'm assumig this is because i'm already on the index page.

how can i load the new data i receive?

i would like to create a dropdown box where am able to write text inside and then it live searches through the results inside the dropdownlist.

what i have tried so far:

Controller:

ViewBag.SagId = new SelectList(db.Sags, "Id", "Emne");

View:

@Html.DropDownListFor(x => x.SagId,(IEnumerable<SelectListItem>)ViewBag.SagId,
new
{
    @class = "form-control"

})

iknow i need some Jquery to do this, but am quite new at this can somebody point me in the right direction?

I have one field on my razor view as following

 @Html.TextBoxFor(model => model.Duration, new { @class = "form-control txtSite input-large rounded-custom", name = "Duration", @type = "number", min = "0", id = "durationId", required = "true", Tabindex = "1", value = "0" })
 @Html.ValidationMessageFor(model => model.Duration, "", new { style = "color: red" })

I used entity model structure in MVC .The field duration is defined in database table "Activity" (Same model i used on razor) as Float. But the entity metadata shows it as Double as follows.

  public Nullable<double> Duration { get; set; }

I used partial class as Activity.cs for required validations as follows

  [MetadataTypeAttribute(typeof(Activity.Metadata))]
    public partial class Activity
    { 
      internal sealed class Metadata
       {
         [Required(ErrorMessageResourceType = typeof(Resources.Common), ErrorMessageResourceName = "PleaseEnterDuration")]
          public Nullable<double> Duration { get; set; }
       }
    }

on Controller my code is like this

[HttpPost]
    public ActionResult AddActivity(Activity model)
    {
        if (ModelState.IsValid)
            {
              //Some Code
            }
    }

The strange is my code works well for float values when my Resource language to display labels is English and its not working when i change it into another language (french).here ModelState.IsValid returning false. And I am getting error as

"The value 3.5(any float value) is invalid for Duration." 

how to fix it for another resource language?. Any help will be appreciated

This question already has an answer here:

I've got a form done in Razor. The user can choose between two actions to take with the data they fill in to that form,

SaveCurrentProgress(User user)

...which allows the user to save the current state of the form and come back to it later. or:

SubmitFinalVersion(User user)

Which saves the form data and then renders it read-only.

I know how to use Html.BeginForm() to pass an object to a single action/controller, but how do I code it so the user can pass the object to one of the two actions?

I currently have the logic below in my model:

    IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
    {
        if (conditionIsTrue)
        {
            if (conditionIsTrue)
            {
                yield return new ValidationResult("First condition", new[] { "InputA" });
            }

            if (conditionIsTrue)
            {
                yield return new ValidationResult("Another condition", new[] { "InputA" });
            }
        }
    }

When the code validates, only "First condition" is showing in my asp-validation-for Tag Helper:

<span asp-validation-for="InputA" class="text-danger"></span>

"Another condition" does not get rendered to the screen. Is there a way to modify the asp-validation-for Tag Helper to display all the messages? I came across this post (http://stackoverflow.com/a/8238907/1193140), but it is using a HtmlHelper.

I have used a class library which is being called by Web Application and Windows service. All of them are contained in a single solution.

I want to execute some code in the class library based on the call of application (Web Application/Windows service). I came across Compilation symbols and tried to implement it but that didn't work.

Please find below code:

#if WEB
        //call from web 
        //perform operation related to web
#endif
#if WindowsService
        //call from WindowsService
        //perform operation related to WindowsService
#endif

I have set the Compilation symbol "WEB" and "WindowsService" in my Web project and Windows Service project respectively by going to Build tab of Project properties.

Note: If I set the Compilation symbol in my class library project, then it works. But it doesn't satisfy my requirement.

Any help or new suggestion would be helpful!!

This question already has an answer here:

I copied a line from razor view to my .cs file by mistake, and it can be compiled. why? and what's the difference between the marked 2 lines? thanks. enter image description here

I have a certain view with a form in Ajax, i want to be able to submit it and if the reCaptach code return false i want to show an error. Here is the form:

@using (Ajax.BeginForm("CreditCard", null, new AjaxOptions { UpdateTargetId = "deposit", InsertionMode = InsertionMode.ReplaceWith, LoadingElementId = "deposit-from-loader", LoadingElementDuration = 300, }, new { id = "deposit" }))
{
<div class="g-recaptcha" data-sitekey="6LcaqxYUAAAAAAWEs5XKsWGuOS7vzRlOjbIEe5jY"></div>
@Html.ValidationMessage("captchaError")
<div class="row">
    <div class="row-item" style="width: 275px;">
        <div id="loading_gif" style="display:none; text-align: right;margin-right: 27px;">
            <img src="/img/loading.gif" border="0" alt="">
            <span style="color:black;display: inline-block;padding-left: 10px;padding-top: 6px;vertical-align: top;">
                @WebContent.Get(pageNameForContent, "FormAjaxMessage", false, "Depositing to your account...")
            </span>
        </div>
        <input type="submit" class="btn yellow" value="@WebContent.Get(pageNameForContent, "FormSubmitButton", false, "Deposit Funds")" id=" edit-submit" name="op">
    </div>
</div>
}

Here is the controller for rendering the form with details:

[HttpGet]
    public async Task<ActionResult> CreditCard(string psp = null)
    {
        this.SetFunctionalPageTitle(FunctionalPagesNames.DepositCreditCard);
        if (User.Identity.GetFullUser().BlockAllDeposit || User.Identity.GetFullUser().BlockCreditCardDeposit)
            return RedirectToAction(nameof(DepositBlockedMessage), new { ccSource = true });
        var model = new DepositCreditCardViewModel
        {
            FirstName = User.Identity.GetFullUser().Lead.FirstName,
            LastName = User.Identity.GetFullUser().Lead.LastName,
            Email = User.Identity.GetFullUser().Lead.Email,
            Phone = User.Identity.GetFullUser().Lead.PhoneNumber?.Replace(" ", ""),
            Currency = User.Identity.CurrentAccount().BaseCurrency,
            CountryId = (await User.GetCountryAsync())?.Id ?? 0,
            Address = User.Identity.GetFullUser().Lead.Address,
            City = User.Identity.GetFullUser().Lead.City,
            ZipCode = User.Identity.GetFullUser().Lead.ZipCode,
            LimitToPspName = psp,
        };

        await SetViewDdlLogins();


        var cardAssocians = FxEnumHelper.GetDisplayNameInterpretor<CreditCardAssociation>()
            .Where(a => a.Value != CreditCardAssociation.Amex)
            .Select(a => new { Text = a.Key, Value = a.Value.GetHashCode() }).ToList();
        ViewBag.CardAssociation = new SelectList(cardAssocians, "Value", "Text");

        ViewBag.DdlExpirationMonth = Enumerable.Range(1, 12)
                                    .Select(a => new SelectListItem { Text = a.ToString(), Value = a.ToString() })
                                    .ToArray();

        ViewBag.DdlExpirationYear = Enumerable.Range(DateTime.Now.Year, 20)
                                    .Select(a => new SelectListItem { Text = a.ToString(), Value = a.ToString() })
                                    .ToArray();

        ViewBag.CountryId = new SelectList(LocalCache.Countries, "Id", "Name");
        ViewBag.StateCodeCanada = new SelectList(LocalCache.CanadaStateCodes(), "Key", "Value");
        ViewBag.CanadaCountryId = LocalCache.Countries.First(a => a.Iso3166_1Alpha2Code == "CA").Id;

        SetViewMinimumAmount();
        return View(model);
    }

Here is the controller after posting:

[HttpPost]
    public async Task<ActionResult> CreditCard(DepositCreditCardViewModel model)
    {
        var response = Request["g-recaptcha-response"];
        string secretkey = "6LcaqxYUAAAAAHWGSHPzGwTmveF7ce_Xbg2gvPnl";
        var client = new WebClient();
        var resultcaptcha = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretkey, response));
        var obj = JObject.Parse(resultcaptcha);
        var status = (bool)obj.SelectToken("success");
        var message = status ? "Google reCaptcha validation success" : "Google reCaptcha validation failed";
        if (!status)
        {
            ModelState.AddModelError("captchaError", message);
            //Need to implement logic to return to the view and not resubmit.
        }
        var paymentRequest = model.ToPaymentRequest();
        paymentRequest.IsTest = _DepositTest;
        paymentRequest.UserIpAddress = Main.GetIP4Address();

        //var sessionInfo = PaymentSessionInfo.Create(model.Login, paymentRequest.Currency, paymentRequest.Amount, _DepositTest);
        //User.Identity.SetOngoingPaymentInfo(sessionInfo);
        //paymentRequest.PaymentId = sessionInfo.Id;
        paymentRequest.CultureSymbol = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
        var country = await _Db.Countries.FindAsync(model.CountryId);
        paymentRequest.CountryIso3166_1Alpha2Code = ViewBag.CountryIso = country.Iso3166_1Alpha2Code;
        var ip2location = await Main.Ip2Location.FindV4Async(paymentRequest.UserIpAddress);
        if (ip2location != null)
        {
            paymentRequest.CountryIsoByIp = ip2location.CountryIsoCode;
        }
        var pspManager = GetPspManager();
        var result = await pspManager.StartTransaction(paymentRequest);
        return await ViewByPpsResult(result);
    }

I want to be able to return an error message in case it didn't went through. As you can see i tried using ModelState.AddModelError - my question is - what view should i return? when i try returning the CreditCard view it's not working.

Iam writing a code to delete an image, here a delete icon image is passing appending on all the images and when I click on the Image it shows an error that A potentially dangerous Request.Path value was detected from the client (<).

my controller

    [Route("Galleries/DeleteImage")]
    public async Task<ActionResult> DeleteImage(int id/*, int Id*/)
    {
        Gallery gallery = await db.Galleries.FindAsync(id);

        if (gallery != null)
        {
            db.Galleries.Remove(gallery);
            await db.SaveChangesAsync();
        }

        return RedirectToAction("Gallery");
    }

this controller to delete the image and the view page is

<div class="gallery_cata">
<div class="container">
    <div class="row">
        @for (var j = 0; j < Model.Count(); j++)
        {
            <div style="margin:5px; float:left;overflow:hidden; width:100px;">
                <a id="ShowImage" class="fancybox-button" data-rel="fancybox-button"
                   title="Photo" href="@Url.Content("~/Upload_Files/" + @Html.DisplayFor(m => m[j].Image))">
                    <div class="zoom" style="height:100px;">
                        <img src="@Url.Content("~/Upload_Files/" + @Html.DisplayFor(m => m[j].Image))" class="imgBox" />
                        <div class="zoom-icon"></div>
                    </div>
                </a>
                <div>
                    @Html.Raw(Html.ImageActionLink("DeleteImage", "DeleteImage", "Hospitals", new { id = @Html.HiddenFor(m => m[j].Id}), null, "~/assets/img/delete.png"))
                </div>
                </div>

                }
            </div>
</div>

When I run the application error occures, I think the problem is n my imageactionlink, can anyone please help me to rectify my error. Please help to write the code correctly I will be so thankful for you .

Below is Button click code for import XL data to sql table using C# asp.net c#

protected void btn_bulkupload_PositionInfo_Click(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    string status = string.Empty;

    string sWorkbook = "[Sheet1$]";
    string Status = string.Empty;
    string Count = string.Empty;
    string root = Request.ServerVariables["APPL_PHYSICAL_PATH"] + "Data\\Contact_Master_Data";
    if (FileUpload_PositionInfo.PostedFile.ContentLength > 0)
    {
        string s1 = FileUpload_PositionInfo.PostedFile.FileName;
        int pos = s1.LastIndexOf('\\') + 1;
        string s2 = s1.Substring(pos);
        string filename = GetRandomPasswordUsingGUID(8) + ".xls";
        string filename1 = GetRandomPasswordUsingGUID(8);
        string filepath = Request.ServerVariables["APPL_PHYSICAL_PATH"] + "Contact_Master_Data\\/" + filename;
        FileUpload_PositionInfo.PostedFile.SaveAs(filepath);
        string sExcelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=YES';";
     //   string sExcelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0;HDR=YES';";

        OleDbConnection OleDbConn = new OleDbConnection(sExcelConnectionString);
        try
        {
            string query = "SELECT * FROM " + sWorkbook;
            OleDbCommand OleDbCmd = new OleDbCommand(query, OleDbConn);
            OleDbConn.Open();
            OleDbDataReader odr = OleDbCmd.ExecuteReader();
            //string BatchId = string.Empty, CandidateName = string.Empty, LoginId = string.Empty, Password = string.Empty;

            while (odr.Read())
            {
                if (odr[0].ToString() != "")
                {
                 //   bo.Dateused = DateTime.ParseExact(odr[0].ToString(), "MM/dd/yyyy", CultureInfo.InvariantCulture);//ReceivedDate

                 //   this.Text = "22/11/2009";

                    bo.Dateused = DateTime.ParseExact(odr[0].ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture);

                }
                else
                {
                    string defaultdate = "01/01/1900";
                    bo.Dateused = DateTime.ParseExact(defaultdate.ToString(), "MM/dd/yyyy", CultureInfo.InvariantCulture);//ReceivedDate
                }
                bo.Para1 = odr[1].ToString();//Year
                bo.Para2 = odr[2].ToString();//Company
                bo.Para3 = odr[3].ToString();//ContactPerson
                bo.Para4 = odr[4].ToString();//Designation
                bo.Para5 = odr[5].ToString();//Role
                bo.Para6 = odr[6].ToString();//DesignationLevel
                bo.Para7 = odr[7].ToString();//Landline
                bo.Para8 = odr[8].ToString();//Mobile
                bo.Para9 = odr[9].ToString();//Email
                bo.Para10 = odr[10].ToString();//Address
                bo.Para11 = odr[11].ToString();//Location
                bo.Para12 = odr[12].ToString();//State
                bo.Para13 = odr[13].ToString();//Website
                bo.Para14 = odr[14].ToString();//SourceContact
                bo.Para15 = odr[15].ToString();//SourceType
                bo.Para16 = filename1;//File Name   
                bo.Para17 = Session["EmailId"].ToString();//Sessoin Emailid
                bo.Para18 = this.Page.Request.ServerVariables["REMOTE_ADDR"];
                bl.Admin_Insert_Bulk_Contact_Preview(bo, out Status);
            }
            OleDbConn.Close();
            if (Status == "Success")
            {
                Response.Redirect("CD_Validate_Contact.aspx?FileName=" + filename1.ToString() + "");
            }
            else
            {
                // lbl_Msg.Visible = true;
                // lbl_Msg.Text = Status;
            }
        }
        catch (Exception ee)
        {
            Status = ee.Message.ToString();
            lbl_Msg.Visible = true;
        }
    }

}

Please check the below Image how Empty data is inserting, the issue only where inserting numbers, there no issue with character insertiong field.

enter image description here

I am working on a simple project, where I have a asp.net core library named "BusinessApiClient" version-1.6 and have a web application project named "MyWebProject". I want to add "BusinessApiClient" in "MyWebProject" as reference. But my problem is its always showing error in reference list.

enter image description here

Project.json :

enter image description here

Don't know why its showing error !!! Hope will get any help. Thanks in advance.

I am working on Asp.net form as follows

<form runat="server" id="form">
                <label>Select Category <span>*</span></label>
                <asp:DropDownList ID="DropDownList1" runat="server">
                    <asp:ListItem>Mobiles</asp:ListItem>
                    <asp:ListItem>Electronics and Appliances</asp:ListItem>
                    <asp:ListItem>Cars</asp:ListItem>
                    <asp:ListItem>Bikes</asp:ListItem>
                    <asp:ListItem>Furniture</asp:ListItem>
                    <asp:ListItem>General</asp:ListItem>
                </asp:DropDownList>
                <div class="clearfix"></div>
                <label>Ad Title <span>*</span></label>

                <asp:TextBox ID="txt_title" class="phone" runat="server"></asp:TextBox>
                <div class="clearfix"></div>
                <label>Ad Description <span>*</span></label>
                <%--<textarea class="mess" placeholder="Write few lines about your product"></textarea>--%>
                <asp:TextBox ID="txt_Body" class="mess" placeholder="Write few lines about your product" TextMode="multiline" Style="resize: none" Width="770px" Height="150px" Wrap="true" runat="server" Font-Bold="True"></asp:TextBox>
                <div class="clearfix"></div>
                <div class="upload-ad-photos">
                    <label>Photos for your ad :</label>
                    <div class="photos-upload-view">

                        <asp:ImageButton ID="ImageButton1" UseSubmitBehavior="false" OnClientClick="return chooseFile();" ImageUrl="Images/Capture.JPG" runat="server" />

                        <asp:FileUpload ID="FileUploadControl" runat="server" Visible="False" />


                        <div id="messages">
                            <p>Status Messages</p>
                        </div>
                    </div>
                    <div class="clearfix"></div>

                </div>
                <div class="personal-details">

                    <label>Your Name <span>*</span></label>
                    <asp:TextBox ID="txt_name" class="name" runat="server"></asp:TextBox>
                    <div class="clearfix"></div>
                    <label>Your Mobile No <span>*</span></label>

                    <asp:TextBox ID="txt_phn" class="phone" runat="server"></asp:TextBox>
                    <div class="clearfix"></div>
                    <label>Your Email Address<span>*</span></label>

                    <asp:TextBox ID="txt_email" class="email" runat="server"></asp:TextBox>
                    <div class="clearfix"></div>
                    <p class="post-terms">By clicking <strong>post Button</strong> you accept our <a href="terms.html" target="_blank">Terms of Use </a>and <a href="privacy.html" target="_blank">Privacy Policy</a></p>

                    <asp:TextBox ID="post_sub" Text="Post" type="submit" runat="server"></asp:TextBox>
                    <div class="clearfix"></div>
            </form>

Where I want to call a hidden fileupload when Imagebutton is clicked using JavaScript as follows:

 <script type="text/javascript">
    function chooseFile() {
        document.getElementById("#FileUploadControl").click();
        alert("grt");
        return false;

    }
</script>

But, I was not able to call the function instead page reloads, as you can see I am returning false in the function also. Please guide me to make this work.

i am new to Asp.net MVC framework.I created web application MVC .It's has application db context login and registration model,controller and view. In this place my issue..I can't create user list for view same db context because it generate path error.

I try another way: I create user db context and view.but it not provide user list because it's new db context and I it is generate already have email and username in initial create context .How to join the application db context and user db context for generate view or how to get needed entity data only in existing database for viewing purpose.

I've successfully made a working jQuery.validation form for my site in just HTML, CSS and JS (with dependencies: jQuery and Validation). The problem is when I'm in a clean ASP.NET Core web project and I use the exact same code, it just doesn't seem to use my custom validation parameters in JavaScript

The validation works in all cases. However, my custom [options] for .validate([options]) don't seem to work on ASP.NET Core

Example of the working code: JSFiddle

HTML:

<form method="post">
<fieldset>
    <div class="master">
      <input name="name" id="name" placeholder="Name" minlength="2" maxlength="40" required />
    </div>
    <div class="master">
      <input name="email" id="email" placeholder="Email Address" type="email" required />
    </div>
    <div class="master">
      <input name="company" placeholder="Company Name" />
    </div>
    <div class="master">
      <input name="website" placeholder="Website" type="url" required />
    </div>

    <button type="submit">Next</button>
</fieldset>
</form> 

CSS:

.master {
  padding: 10px;
  background-color: white;
}

.has-error {
  background-color: red;
}

.has-success {
  background-color: green;
}

JS:

$('form').validate({
    // This disables the default validation notifications to the user.
    // Instead I'll be using CSS colors to notify users of valid or invalid fields
    errorPlacement: function (error, element) { },

    // Invalid field produces a red-background in parent element
    highlight: function(element) {
    $(element).parent().addClass('has-error').removeClass('has-success');
  },

  // Valid field produces a green-background in parent element
  unhighlight: function(element) {
    $(element).parent().removeClass('has-error').addClass('has-success');
  }
});

My JavaScript .validate([options]) does 3 things:

  1. Remove jQuery.validation's default notification option
  2. If <field> is INVALID, parent element background-color is red
  3. If <field> is VALID, parent element background-color is green

Note:

  • Updated my ASP.NET Core (1.1) to the latest stable version
    • Downgraded to ASP.NET Core 1.0 to test
  • Added latest jQuery via bower, local and CDN (for testing)
  • Added latest Validate via bower, local and CDN (for testing)
    • According to Validate's website certain versions of jQuery has to be used for compatibility. I tested all the versions via bower, local and CDN
  • Made a raw HTML, CSS and JS version with everything stripped out (dependencies included) in JSFiddle, CodePen and local. Everything worked perfectly but not in ASP project.
  • External or Inline JavaScript, no changes.

My conclusion: The validation works in all cases, which means both ASP.NET Core applications and plain HTML - CSS - JS have properly functional validation.

The only thing that doesn't work is when I provide [options] in my $('form').validate([options]); in a ASP.NET Core application. I'm not sure why my options aren't being used.

Official jQuery.validate page on .validate([options])

I have a MVC application where I am rendering PartialViews that contain different dynamically rendered forms. All of my inputs are getting their Metronic styles except the checkboxes inside of PartialViews.

View CheckBox:

Checkbox in View

HTML/Razor:

<input class="categoryCb" checked="checked" type="checkbox" id="@("cb"+@category.CategoryID)" value="" />

PartialView Checkbox:

Checkbox in PartialView

HTML/Razor:

 <input checked="checked" value="" type="checkbox" id="@("cbItem"+@item.ItemNo)" />

Any thoughts?

I have a table with a bunch of rows with the same dropdown options. What I want to do is on a button click, grab the selected values for the dropdown that the row that the button is in.

<select class="items" data-value="@item.Id">
    <option>None</option>
    @foreach (var item in ViewBag.Items)
    {
       <!option value="@(item)">
           @(item.Title)
       </!option>
    }
</select>

What I have tried to do is:

var button = $(event.target);
var itemClass = button.closest(".items");
var selectedItem = itemClass.options[this.selectedIndex].text;

This does correctly grab the class, but it can't seem to get text of the selected item.

I want to show a glyphicon-user at the end of a textBoxFor control in MVC C# but I can't accomplished yet, in the code I show (razor commented @* *@) the span tags that I tried in order to get the glyphicon but didn't work out, could you please help me

            <div class="form-group">
                @Html.LabelFor(model => model.usuario, new { @class = "control-label col-md-2" })  
                <div class="col-md-10">
                    @*<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>*@

                    @Html.TextBoxFor(model => model.usuario, new { @class = "form-control", @placeholder = "Usuario", @type = "text" })
                    @*<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>*@
                    <p class="text-danger"> @Html.ValidationMessageFor(model => model.usuario)</p>
                </div>
            </div>

I would like to add items that fit certain conditions to an array. I tried add System.Linq. But it is still not working.

@{
Sitecore.Data.Database database = Sitecore.Data.Database.GetDatabase("master");
Sitecore.Data.Items.Item[] items = database.SelectItems("fast:/sitecore/xxxxxx");
Sitecore.Data.Items.Item[] dictionary;


    foreach (Sitecore.Data.Items.Item currentItem in items){
        Sitecore.Data.Fields.MultilistField multilistField = currentItem.Fields["xxx"];
        if (multilistField != null)
        {

          foreach (Sitecore.Data.ID id in multilistField.TargetIDs)
          {
            Sitecore.Data.Items.Item targetItem = Sitecore.Context.Database.Items[id];

            if(targetItem.Fields["Label"].Value.ToLower() == "c"){
               dictionary = currentItem.ToArray();
            }
          }
        }
    }
}

I'm building a login form with Web API(ASP.NET), but dunno how to do it.

At first what I thought was to send a POST with the username and password and query it through the database, if they user info is correct then redirect the user to the welcome screen.

But i thing this approach is really old/plain, I'm just doing it to learn so I don't need something fancy.

I've reading and found something called token based authentication, can you briefly explain me what are the benefits of using this method vs the method that I thought?

BTW to show the data related to that user that logged in, I thought to store the username in a variable and then query through the database and see if the data belongs to the user, is this approach right?

Or how can I do it to show the data that is bind to a certain user.

THANKS