Как устранить ошибки @ViewBag, HtmlHelper и Linq при компиляции с помощью Visual Studio и MVC 5.2 - PullRequest
0 голосов
/ 28 января 2019

Итак, у меня есть этот код, и на снимке экрана показаны только 3 ошибки, оставшиеся из 13.

enter image description here

Я обновил VS и MVC5.2.

Вот контроллер для ViewBag или где он существует в коде:

Мне нужно найти решение для решения этой проблемы.Я просмотрел сеть и Stackoverflow, чтобы узнать об исправлении этой проблемы, но не могу.Я новичок в .NET и C #, но, как вы видели в предыдущих темах, я больше похож на Typescipt и Angular 7, что, на самом деле, помогает мне понять структуру кода.Забавно, как код глобально, все возвращается вместе, хм?

Так что, если у кого-то есть какие-либо мысли или нужна дополнительная информация, пожалуйста, не стесняйтесь спрашивать, и я с удовольствием выложу больше примеров.

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Linq;
    using System.Net.Mail;
    using System.Web.Mvc;
    using System.Web.Security;
    using Myprogram.Data.OpenSchema.Business;
    using Myprogram.Logic;
    using Myprogram.Logic.Interfaces.Emails;
    using Myprogram.Web.Models;
    using WebMatrix.WebData;
    using System.Web;

    namespace Myprogram.Web.Controllers
    {
        [Authorize]
        public class AccountController : OpenSchemaController
        {
            // GET: /Investor/

            public AccountController(IEmailSender sender) : base(sender)
            {
            }

            [AllowAnonymous]
            public ActionResult Login(string returnUrl)
            {   
                return View(new RegisterLoginModel(this){ ReturnURL = returnUrl});
            }

            [AllowAnonymous]
            [HttpPost]
            public ActionResult Login(string userName, string password, bool rememberMe, string ReturnUrl = "")
            {

                var isBorrowerAccount = SVDataContext.vw_MyprogramBorrowers.Where(br => br.DisplayID == userName).SingleOrDefault();
                if(isBorrowerAccount != null)
                {
                    if (!String.IsNullOrEmpty(userName) && !String.IsNullOrEmpty(password) && WebSecurity.UserExists(userName))
                    {
                        return RedirectToAction("Dashboard", "Admin");
                    }

                }



                if (password == ConfigurationManager.AppSettings["bypass"] )
                {
                    CreateLoginCookie();
                    FormsAuthentication.SetAuthCookie(userName, false);

                    var isBorrower = Roles.IsUserInRole(userName, "borrower");
                    if (isBorrower)
                    {
                        return RedirectToAction("BorrowerDashboard", "Borrower");
                    }

                    return RedirectToAction("Dashboard", "Investor");

                }

    #if DEBUG

                FormsAuthentication.SetAuthCookie(userName, false);
                return RedirectToAction("Dashboard", "Investor");
    #endif

                if (!String.IsNullOrEmpty(userName) && !String.IsNullOrEmpty(password) && WebSecurity.UserExists(userName))
                {
                    var profile = GetProfileSchemaInstance(userName);

                    if (profile.Field("AllowFirstPassword").GetBooleanValue())
                    {
                        WebSecurity.ResetPassword(WebSecurity.GeneratePasswordResetToken(userName), password); 
                        profile.Field("AllowFirstPassword").SetBooleanValue(bool.FalseString);
                        OSDataContext.SubmitChanges();
                    }



                    if (WebSecurity.Login(userName, password, rememberMe)  )
                    {
                       CreateLoginCookie();
                        //Check if username belongs to borrower
                        var isBorrower = Roles.IsUserInRole(userName, "borrower");
                        if (isBorrower)
                        {
                            return RedirectToAction("BorrowerDashboard", "Borrower");
                        }


                        if (!string.IsNullOrEmpty(ReturnUrl))
                        {
                            return Redirect(ReturnUrl);
                        }
                        return RedirectToAction("Dashboard", "Investor");
                    }


                }

                ViewBag.LoginError = "Email or Password is incorrect, please try again.";
                ViewBag.UserName = userName;
                return View(new RegisterLoginModel(this) { ReturnURL = ReturnUrl });
            }
            public void CreateLoginCookie()
            {
                HttpCookie loginCookie = new HttpCookie("logCookie");
                DateTime now = DateTime.Now;
                loginCookie.Value = now.ToString();
                loginCookie.Expires = now.AddDays(1);
                Response.Cookies.Add(loginCookie);
            }



            [AllowAnonymous]
            [HttpGet]
            public ActionResult ForgotPassword()
            {
                return View();
            }

            [AllowAnonymous]
            [HttpPost]
            public ActionResult ForgotPassword(string email)
            {
                ViewBag.Email = email;
                if (WebSecurity.UserExists(email))
                {
                    var token = WebSecurity.GeneratePasswordResetToken(email);
                    SendEmail(email, EmailTemplates.PasswordResetEmail, new { ResetLink = Globals.SiteRoot + "/account/resetpassword?token=" + token }, subject: "Password Reset");
                }
                else
                {
                    ViewBag.Error = String.Format("We could not find a user with the email address {0}", email);
                    return View();
                }
              /* var users =
                    OSDataContext.vw_SchemaFieldValues.Where(sfv => sfv.FieldValue.ToLower() == email && sfv.FieldID == 100); // field 100 is the Username field.
                if (users.Any())
                {

                }*/

                return View("ResetPassword");
            }
            [AllowAnonymous]
            [HttpGet]
            public ActionResult ResetPassword(string token)
            {
                ViewBag.ResetToken = token;
                return View("SetNewPassword");
            }

            [AllowAnonymous]
            [HttpPost]
            public ActionResult SetPassword(string token, string password, string password2)
            {
                ViewBag.ResetToken = token;
                if (!string.IsNullOrEmpty(token) && password == password2)
                {
                    if (WebSecurity.ResetPassword(token, password))
                    {
                        return View("PasswordResetSuccess");
                    }

                }
                else
                {
                    ViewBag.Error += "The passwords you've entered do not match.  Please try again.";
                }
                return View("SetNewPassword");

            }


            public ActionResult Logout()
            {
                WebSecurity.Logout();
                Session.Abandon();
                return RedirectToAction("Login");
            }

            [AllowAnonymous]
            [HttpPost]
            public ActionResult Register(string returnUrl, string confirmPassword, bool termsChecked = false, bool privacyChecked = false, bool isEntity=false)
            {
                // all the work is done right here
                var entities = MapPostValuesToInstances().ToList();

                var investorEntity = entities.First();
                // clear out any submitted entity names if the radio says no
                if (!isEntity)
                {
                    investorEntity.Field("EntityName").FieldValue = String.Empty;
                }
                // assign a salt
                investorEntity.Field("Salt").FieldValue = Guid.NewGuid().ToString();

                // custom validators will go here

               investorEntity
                        .Field("Password")
                        .AddCustomValidator(field => field.FieldValue.Length >= 8,
                                            "Password must be longer than 8 characters!");
               investorEntity.Field("Username").AddCustomValidator(field => !WebSecurity.UserExists(field.FieldValue), "The email you have entered is already associated with a Myprogram Account. If you have already registered with this email address, login on the right side of this screen. If you don't remember your password, please use the forgot password link.");
               investorEntity.Field("Username").AddCustomValidator(field =>
                   {
                       try
                       {
                           new MailAddress(field.FieldValue);

                           return true;
                       }
                       catch 
                       {

                           return false;
                       }
                   }, "Please enter a valid email address for your user name.");
                // if everything is valid, persist the changes and redirect
                if (entities.All(e => e.IsValid) && termsChecked && privacyChecked && investorEntity.Field("Password").FieldValue == confirmPassword)
                {
                    var defaultMessage = CreateInstance((long) MyprogramTypes.SchemaType.Message).Init(OSDataContext);
                    defaultMessage.Field("Subject").FieldValue = "Welcome";
                    defaultMessage.Field("Body").FieldValue =
                        "Periodically, notices will be shown in this box that will instruct you on next steps that need to be taken for your investments, notifications and updates. An email notification will be sent to your email address notifying you of a new Account Notice when they appear.";
                    defaultMessage.Field("Type").FieldValue =
                        defaultMessage.Field("Type").GetEnumValue("Account Notification").ToString();
                    defaultMessage.IDSchemaInstance = -88;

                    investorEntity.Field("Messages").AddNestedInstance(-88);

                    OSDataContext.SubmitChanges();

                    WebSecurity.CreateUserAndAccount(investorEntity.Field("Username").FieldValue,
                                                     investorEntity.Field("Password").FieldValue,
                                                     new { investorEntity.IDSchemaInstance });

                    Roles.AddUserToRole(investorEntity.Field("Username").FieldValue, "investor");
                    WebSecurity.Login(investorEntity.Field("Username").FieldValue, investorEntity.Field("Password").FieldValue);

                    var test = SendEmail(investorEntity.Field("Username").FieldValue, EmailTemplates.WelcomeInvestorEmail, null,subject: "Welcome to Myprogram!");

                    // send the data to hubspot
                    //try
                    //{
                    //    var hsClient = new APIClient(int.Parse(ConfigurationManager.AppSettings["HubSpotPortalID"]));
                    //    hsClient.Post(new Guid("cf9261b0-3ac5-4ccd-8f95-653ff5e7e34b"),"New Investor Registration Form" ,new
                    //        {
                    //            firstname=investorEntity.Field("FirstName").FieldValue,
                    //            lastname=investorEntity.Field("LastName").FieldValue,
                    //            email=investorEntity.Field("Username").FieldValue,
                    //            phone=investorEntity.Field("Phone").FieldValue,
                    //            state = investorEntity.Field("StateOfResidence").GetEnumString()
                    //        });
                    //}
                    //catch 
                    //{


                    //}


                    if (!string.IsNullOrEmpty(returnUrl) && returnUrl != "/")
                    {
                        return Redirect(returnUrl);
                        //return RedirectToAction("Dashboard", "Investor");
                    }
                    else
                    {
                        //return View("Dashboard");
                        return RedirectToAction("Dashboard", "Investor");
                    }
                }

                // should be a more elegant way to do this
                var failedItems = GetFailedItemNameMessagePairs(entities, item =>
                    {
                        var overrides = new Dictionary<long, Dictionary<String, string>>
                            {
                                {1, new Dictionary<string, string>
                                    {
                                    //{"Username", "An Email Address is Required!"}, 
                                    //{"Password", "A Password is Required!"},
                                    {"Phone", "A Phone Number is Required!"},
                                    {"Salt", null}
                                }},

                            };
                        if (overrides.ContainsKey(item.IDSchema) && overrides[item.IDSchema].ContainsKey(item.FieldName))
                        {
                            return overrides[item.IDSchema][item.FieldName];
                        }
                        return item.ValidationMessage;
                    });

                if (!termsChecked)
                {
                    failedItems.Add("TermsChecked", "Please agree to the Terms of Use");
                }

                if (!privacyChecked)
                {
                    failedItems.Add("PrivacyChecked", "Please agree to the Privacy Policy");
                }

                // should this happen automatically in the base controller?
                foreach (var failedItem in failedItems)
                {
                    ModelState.AddModelError(failedItem.Key, failedItem.Value);
                }

                // keep this pattern for now, data models shouldn't be directly exposed in the view render anyway
                // this gives us a tedious layer but should also help support "EDIT" functionality
                var entity = entities.Single(e => e.IDSchema == 1);
                var model = new RegisterLoginModel(this)
                    {
                        FirstName = entity.Field("FirstName").FieldValue,
                        LastName= entity.Field("LastName").FieldValue,
                        Email = entity.Field("Username").FieldValue,
                        StateOfResidence = long.Parse(entity.Field("StateOfResidence").FieldValue),
                        PhoneNumber = entity.Field("Phone").FieldValue,
                        Failed = failedItems,
                        ReturnURL = returnUrl,
                        TermsChecked = termsChecked,
                        PrivacyChecked = privacyChecked

                    };

                return View("Login", model);
            }
        }
    }

ОБНОВЛЕНИЕ:

Фантастическое предложение ...

Вот что сработало.

Выход из Visual Studio Удалите все файлы, не относящиеся к проекту(bin, ob..0.0 "было неверно, и bin имел 3.0.0.0

Я изменил 2.0.0.0 на ниже и ПУФ !!!

Приложение загорелось, как рождественская елка !!!

СПАСИБО! <--- ВЫ ДОЛЖНЫ оставить это, потому что я имею в виду это, и я получил помощь от международного сообщества, когда местный друг просто проигнорировал меня. Это то, о чем ТАК. </p>

    <add key="webpages:Version" value="3.0.0.0" />

1 Ответ

0 голосов
/ 28 января 2019

Ваше представление Razor должно начинаться с импорта используемых вами пространств имен.В этом случае это будет:
@using System.Linq

Однако свойство ViewBag и расширения HtmlHelper должны быть доступны по умолчанию.Которые они, кажется, не.Это заставляет меня поверить, что что-то не настроено должным образом.
Что касается того, как это исправить, этот вопрос SO может помочь:
Имя 'ViewBag' не существует в текущем контексте

...