CS 1061 error on ASP.Net - asp.net

im just start learning asp.net and encounter this error
i've tried many solution from google but still get this error (errr...)
Compiler Error Message: CS1061: 'Exercise1.Visitor' does not contain a definition for 'Name' and no extension method 'Name' accepting a first argument of type 'Exercise1.Visitor' could be found (are you missing a using directive or an assembly reference?)
im using VS2012 with 4.5 Net
this is my code
Model
namespace Exercise1.Models
{
public class Visitor
{
public String Name
{
set;
get;
}
}
}
Controller
namespace Exercise1.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Visitor data)
{
ViewBag.Message= "Hi my name is" + data.Name;
return View();
}
}
}
View
#{
Layout = null;
}
#model Exercise1.Visitor
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
</head>
<body>
<div>
#using(Html.BeginForm())
{
<p>
#Html.LabelFor(m=>m.Name);
</p>
}
</div>
</body>
</html>
btw, this is my first question hehe

Change model to:
#using Exercise1.Models
#model Exercise1.Models.Visitor

Do you have another Vistor class in your project? it's saying Exercise1.Visitor when it should be complaining about Exercise1.Models.Visitor
make sure you're referencing Exercise1.Models.Visitor

Related

How can i pass model to view in asp.net core 5.0 mvc

Im trying to pass that data to my view. I allready look around what can i do or which way i can use or something but im still getting null exception error when i call that ViewBag.passData.
Here its my BaseController :
public class BaseController : Controller
{
public BaseViewModel baseViewModel;
public readonly IUnitOfWork<SiteSetting> _unitOfWorkSiteSetting;
public readonly IUnitOfWork<Category> _unitOfWorkCat;
public BaseController(
IUnitOfWork<SiteSetting> unitOfWorkSiteSetting,
IUnitOfWork<Category> unitOfWorkCat)
{
_unitOfWorkSiteSetting = unitOfWorkSiteSetting;
_unitOfWorkCat = unitOfWorkCat;
baseViewModel = new BaseViewModel
{
SiteSettings = _unitOfWorkSiteSetting.RepositorySiteSettings.GetSiteSettingsByID(2),//1-Admin,2-Shopping,3-WebFair
IsFeaturedCategories = _unitOfWorkCat.RepositoryCategory.IsFeaturedCategoriesAsNoTracing(10)
};
ViewBag.passData = baseViewModel;
}
}
as u can see im filling up my BaseViewModel in that BaseController.
im trying to do that because im calling those data in every page.
when i call that ViewBag.passData in my view,im getting null exception error.
Here its my view :
#model IndexViewModel;
#using Microsoft.Extensions.Configuration
#inject IConfiguration Configuration
#{ ViewData["Title"] = "Anasayfa";
Layout = null;
BaseViewModel baseViewModel = new BaseViewModel();
baseViewModel = ViewBag.passData; ***//The point where i am getting that error***
var siteKey = Configuration.GetSection("GoogleRecaptcha").GetSection("RecaptchaV3SiteKey").Value ?? "";
}
<!DOCTYPE html>
<html lang="tr">
<head>
<partial name="_HeadPartial" />
<!-- RECAPTCHA JS-->
<script src="https://www.google.com/recaptcha/api.js?render=#siteKey"></script>
<!-- RECAPTCHA JS-->
</head>
It goes like that....
I allready check it out my BaseController and its working well.
Thanks for any suggestion!
You can do return View(VieModel)
Then in your .cshtml view you can add #model of the type you passed into the view

debugging the asp.net core web API

I wrote this API in .net. I am trying to call this method through Fiddler and getting the below error message:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /api/allItProjectsLists/Index</pre>
</body>
</html>
Not sure what am I doing wrong. Is there any way, I can put a breakpoint inside method Index and find out what is wrong. Below is my API code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ProjectDetails.Models;
using ProjectDetails.Data;
using ProjectDetails.Interfaces;
namespace ProjectDetails.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AllItProjectsListsController : ControllerBase
{
private readonly KPIContext _context;
private readonly IProject objProject;
public AllItProjectsListsController(IProject _objProject)
{
objProject = _objProject;
}
[HttpGet("/Index")]
public IEnumerable<AllItProjectsList> Index()
{
return objProject.GetAllProjectDetails();
}
[HttpPost]
[Route("api/AllItProjectsLists/Create")]
public int Create([FromBody] AllItProjectsList project)
{
return objProject.AddProject(project);
}
[HttpGet]
[Route("api/AllItProjectsLists/Details/{id}")]
public AllItProjectsList Details(int id)
{
return objProject.GetProjectData(id);
}
[HttpPut]
[Route("api/AllItProjectsLists/Edit")]
public int Edit([FromBody]AllItProjectsList project)
{
return objProject.UpdateProject(project);
}
[HttpDelete]
[Route("api/AllItProjectsLists/Delete/{id}")]
public int Delete(int id)
{
return objProject.DeleteProject(id);
}
[HttpGet]
[Route("api/AllItProjectsLists/GetAppDevList")]
public IEnumerable<AppDev> GetAppDev()
{
return objProject.GetAppDevs();
}
any help with the above debugging will be highly appreciated. In Fiddler, I typed the following URL:
https://localhost:44313/api/AllItProjectsLists/Index
Below is the image from Fiddler:
You need to change [HttpGet("/Index")] to [HttpGet("Index")] on your action for attribute routing.
[HttpGet("/Index")] will be executed for a URL as https://localhost:44313/Index
[HttpGet("Index")] will be executed for a URL as https://localhost:44313/api/AllItProjectsLists/Index
Refer to attribute routing

Viewbag variable in shared view _layout

I would like to use ViewBag values in the shared view of layout but provided from another controller. In particular, I would like to render the principal action and then add few variables, coming from another controller, that are used in a lot of pages (but not in all pages to justify the use of global variables).
Views/Shared/_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/css_custom")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
#Html.Action("myAction", "myController")
<p>Value: #ViewBag.testval </p>
#RenderBody()
</body>
</html>
Controllers/myController.cs
namespace myProject.Controllers
{
public class myController : Controller
{
public void myAction() {
string test_value = "Hey!";
ViewBag.testval = test_value;
}
}
}
In the layout the only Viewbag variables that I can access are the ones of the action target of RenderBody.
You should return that view.
public ActionResult Index()
{
ViewBag.testval = "Test value";
return View();
}

Putting a model on every view

I'm trying to pass my UserModel to every view, so it can show on top the current user information.
This is my BaseViewModel:
public class BaseViewModel
{
public UserModel currentUser { get; set; }
}
BaseController:
public class BaseController : Controller
{
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
UserRepository userRep = new UserRepository();
BaseViewModel model = new BaseViewModel
{
currentUser = userRep.getCurrentUser()
};
base.OnActionExecuted(filterContext);
}
}
HomeController: (default)
public class HomeController : BaseController
{
public ActionResult Index()
{
ListRepository listRep = new ListRepository();
return View(listRep.GetAllLists());//returns IEnumerable<ListModel>
}
}
My shared _layout.cshtml:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - My ASP.NET Application</title>
#Styles.Render("~/Public/css")
</head>
<body>
<header>
#Html.Partial("_Header")
</header>
#RenderBody()
</body>
</html>
and finally, my _Header.cshtml:
<div id="logo">
<h1>Hello #Model.currentUser.username</ h1 >
</div>
But I get this error message when I run it:
'System.Collections.Generic.List' does not contain a definition for 'currentUser'
I thought my BaseViewModel would always get appended
The model in the view is IEnumerable<ListModel> and that is what will be passed to the partial unless you specify a model, for example, using
#Html.Partial("_Header", someOtherModel)
Instead, create a ChildActionOnly method that returns your user data to the _Header.cshtml partial view and in the main view use #Html.Action() to render it
[ChildActionOnly]
public ActionResult _Header()
{
var model = .... // get the model you want to render in the partial
return PartialView(model);
}
and in the main view
#{ Html.RenderAction("_Header", controllerName); }
If you want that in every view, you may consider calling a child action method using Html.Action.
So replace
<header>#Html.Partial("_Header")</header>
with
<header>#Html.Action("Header","YourControllerName")</header>
Now have an action method called Header where you will pass the needed data to it's partial view
[ChildActionOnly]
public ActionResult Header()
{
var vm = new YourHeaderViewModel();
vm.UserName="Shyju"; // Replace with whatever you want.
return PartialView(vm);
}
Where YourHeaderViewModel is your view mode for the header with the properties needed for the header.
public class YourHeaderViewModel
{
public string UserName {set;get;}
}
Now in your Header partial view which is strongly typed to the YourHeaderViewModel class,
#model YourHeaderViewModel
<div id="logo">
<h1>Hello #Model.UserName</ h1 >
</div>
Another possible solution using BaseController.
Instantiate your BaseViewModel model in OnResultExecuting method instead of OnActionExecuted. And save the model in ViewData to access it in _Header partial view.
E.g.
public class BaseController : Controller
{
protected override void OnResultExecuting(ResultExecutingContext filterContext)
{
UserRepository userRep = new UserRepository();
BaseViewModel model = new BaseViewModel
{
currentUser = userRep.getCurrentUser()
};
filterContext.Controller.ViewData["customData"] = model;
}
}
Now you need to pass ViewData to _Header partial view.
E.g.
#Html.Partial("_Header", ViewData["customData"])
In _Header partial view, you can simply access the data.
<div id="logo">
<h1>Hello #Model.currentUser.username</ h1 >
</div>

Using DisplayForModel with MVC4 and the ASPX View Engine

Using ASP.NET MVC4 (.NET 4, C#) on MSVC 2010 SP1, I've noticed that I can pass a class model to a view using Razor and display the model using DisplayModelFor & EditorForModel but when I try to do the same using the ASPX view engine it doesn't work. Why is that? Code snippets from my test project below. Thanks.
My Controller:
namespace MvcApplication1.Controllers
{
public class TestController : Controller
{
public ActionResult Index()
{
TestModelClass c = new TestModelClass();
c.MyInt = 999;
return View(c);
}
}
My Model:
namespace MvcApplication1.Models
{
public class TestModelClass
{
public int MyInt { get; set; }
}
}
My View:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.TestModelClass>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<%Html.DisplayForModel(); %>
</div>
</body>
</html>
Alternate Razor (Works):
#model MvcApplication1.Models.TestModelClass
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#Html.DisplayForModel()
Successful output from Razor version:
Index
MyInt
999
You are missing a :.
The correct syntax should be
<%: Html.DisplayForModel() %>

Resources