I created a button that directs to another page with 3 tabs.
These 3 subtabs has different input text and only using 1 Action [HttpGet].
These are my cases.
I want to save only first tab data, the 2 tabs value will be null
I want to save only second data, the 1st tab and 3rd tab will be null
I want to save all the text input that I've typed under 1st tab, 2nd tab, and 3rd tab.
Here is my code:
[HttpGet]
public ActionResult Create_Data(int productId)
{
var model = BigViewModel();
///rest of code
return View(model)
}
[HttpPost]
public ActionResult Create_Data(BigViewModel model, int productId)
{
int experimentForOverloading = 0;
string experimentAgain = ""
// validates if first tab and doesn't have data inputted, will redirect to Create_SecondTab. Below is just for testing
if (model.FirstTabName == null && model.ThirdTabDirectory == null)
{
// this is where I want to go to route the new Action. But I don't know what to do..
return RedirectToAction("CreateData", new
{
model = BigViewModel,
Id = productId,
experimentForOverloading
}
}
else if (model.SecondTabSalary == null && model.ThirdTabDirectory == null)
{
return RedirectToAction("CreateData", new
{
model = BigViewModel,
Id = productid
experimentAgain
}
}
else
{
return RandomView(); //Testing purposes
}
}
// This is the second case, save only when first tab is empty
[HttpPost]
public ActionResult CreateData(BigViewModel, int bigId, int experimentForOverloading)
{
if(ModelState.IsValid)
{
//.. code here
_context.SaveChanges()
}
else
{
return RandomView(); //Testing purpose
}
}
// This is the first case, save only when second and third tab is empty
[HttpPost]
public ActionResult CreateData(BigViewModel, int bigId, string experimentAgain)
{
if(ModelState.IsValid)
{
//.. code here
_context.SaveChanges()
}
else
{
return RandomView(); //Testing purpose
}
}
Related
User is always null in the second ActionResult and works correctly in the first. Both are in the same Controller.
Only difference I can think of is that the first Page is serving a dynamic page while the second SpecialReports are static files in a folder.
Why is this? Is there a fix?
public ActionResult Page(string it)
{
MVpage page = new MVpage(it);
//some code
if (!page.Content.Published && !User.IsInRole("Admin")) //works fine!
{
Response.StatusCode = 307;
return View("Woops");
}
return View(page);
}
public ActionResult SpecialReports(string name)
{
if (!name.Contains("pdf") && !User.IsInRole("Admin"))//Doesn't work! User==null :(
{
Response.StatusCode = 307;
return View("Woops");
}
return new FilePathResult("~/x/" + name, y);
}
I am showing search results same as searching groups on facebook
enter image description here
I have a relationship Table named CommunityUser in Database having attributes CommunityID and UserID.
Using Partial View I want to show if User not already joined that Community/Group that it will show Join Button else if user already joined that community it will show Leave button.
I have written IsMember() function in my controller that takes two parameters, CommunityID and UserID. This will return true if that Community ID exist against that user ID.
public bool IsMember(string UserID, int CommunityID) {
var Membership = db.Users.Include(x => x.CommunityUsers).Where(s => s.Id.Equals(UserID)).Count();
if(Membership>0)
return true;
else
return false;
}
Now what I actually need is, I want to call this function in an IF condition on my view class. It is not allowing me to call this function on my view Class.
#if (){
<button>#Html.ActionLink("Leave", "LeaveCommunity", new { id = ViewBag.ComID })</button>
}
else
{
<button>#Html.ActionLink("Join", "joinCommunity", new { id = ViewBag.ComID })</button>
}
In your controller you should have a method which will return this view. So in this method you call this function
public ActionResult Index(string UserID, int CommunityID)
{
var hasMembership = IsMember(serID, CommunityID);
return View(hasMembership);
}
In the View it self then you just grab this variable hasMembership you just passed from #model.
#if (Model){
<button>#Html.ActionLink("Leave", "LeaveCommunity", new { id = ViewBag.ComID })</button>
}
else
{
<button>#Html.ActionLink("Join", "joinCommunity", new { id = ViewBag.ComID })</button>
}
Note: it might be wise to create some DTO class for passing data to a view, because you might need to pass multiple value to a view at some point. Plus the whole condition would be more readable
public SomeDTO {
public bool IsMember {get;set}
public List<Community> Communities {get;set;}
}
public ActionResult Index(string UserID, int CommunityID)
{
var hasMembership = IsMember(serID, CommunityID);
var listOfCommunities = _repo.GetComunities();
var dto = new SomeDTO
{
IsMember = hasMembership,
Communities = listOfCommunities
}
return View(dto);
}
#if (Model.IsMember){
// do or do not something
}
I am stuck on a problem implementing LINQ properly on my model. Right now I have it so that when the user clicks on the "list tracks" view they will receive a listing of every song in the DB. What i want to do, is add another link at the top such as "pop tracks" and have it when the user clicks on it, it will sort all the songs by their GenreId (pop) which is 9. I am unsure how to accomplish this as i don't understand how you would return multiple views from 1 index() method (if that's even how i would do it?). Any help is appreciated.
I am now receiving this error:
xception Details: AutoMapper.AutoMapperMappingException: Missing type
map configuration or unsupported mapping.
Mapping types: Genre -> TrackBase Assignment_3.Models.Genre ->
Assignment_3.Controllers.TrackBase
Source Error:
Line 74: { Line 75: var AllPop = ds.Genres.Where(p
=> p.GenreId == 9); Line 76: return mapper.Map>(AllPop); Line 77: } Line
78:
Manager.cs:
public IEnumerable<TrackBase> TrackGetAll()
{
return mapper.Map<IEnumerable<Track>, IEnumerable<TrackBase>>(ds.Tracks);
}
public IEnumerable<TrackBase> TrackGetAllPop()
{
var AllPop = ds.Genres.Where(p => p.GenreId == 9);
return mapper.Map<IEnumerable<TrackBase>>(AllPop);
}
TrackController.cs:
public ActionResult Index(int? genreid)
{
if (genreid.HasValue && genreid.Value == 9)
{
return View(m.TrackGetAllPop());
}
return View(m.TrackGetAll());
}
AutoMapperConfig.cs:
cfg.CreateMap<Models.Track, Controllers.TrackBase>();
cfg.CreateMap<Controllers.TrackBase, Controllers.TracksController>();
You need to pass the genre id to Index action method and filter the songs accordingly. Change your controller to this
public ActionResult Index(int? genreid)
{
if (genreid.HasValue && genreid.Value == 9)
{
// return all pop songs to the view
return View(m.TrackGetAllPop());
}
// return all songs to the view
return View(m.TrackGetAll());
}
then in your index
#Html.ActionLink("All Tracks", "Index") |
#Html.ActionLink("Pop Tracks", "Index", new { genreid = 9})
You also have a problem with TrackGetAllPop method
public IEnumerable<TrackBase> TrackGetAllPop()
{
var AllPop = ds.Genres.Where(p => p.GenreId == 9);
return mapper.Map<IEnumerable<TrackBase>>(AllPop);
}
The above method returns IEnumerable<TrackBase> but you're querying from ds.Genres instead of ds.Tracks, so that's why you got the error. Assuming Track table has GenreId as the foreign key to the Genre table, TrackGetAllPop method should be like below
public IEnumerable<TrackBase> TrackGetAllPop()
{
var AllPop = ds.Tracks.Where(p => p.GenreId == 9);
return mapper.Map<IEnumerable<TrackBase>>(AllPop);
}
More General Solution
The above will work for this particular case, however you can make it more general for other genres too. Add this method in Manager.cs
public IEnumerable<TrackBase> TrackGetByGenre(int genreId)
{
var result = ds.Tracks.Where(p => p.GenreId == genreId);
return mapper.Map<IEnumerable<TrackBase>>(result);
}
and change your controller to below
public ActionResult Index(int? genreid)
{
if (genreid.HasValue)
{
// return songs based on the passed genreid to the view
return View(m.TrackGetByGenre(genreid.Value));
}
// return all songs to the view
return View(m.TrackGetAll());
}
I am developing a website using asp.net mvc 4 & EF6. I want to pass a string value as a parameter in a Url.action link. However, whenever I click on the link I get this error:
The argument types 'Edm.Int32' and 'Edm.String' are incompatible for this operation. Near WHERE predicate, line 1, column 76.
This is the code that creates it:
Controller
public ActionResult Edit(string EditId)
{
if (Session["username"] != null)
{
UserInfo uinfo = db.UserInfoes.Find(EditId);
return View(uinfo);
}
else
{
return RedirectToAction("HomeIndex");
}
}
View
<a class="btn btn-info"
href="#Url.Action("Edit", "Home", new { EditId = item.regno.ToString() })"><b>Edit</b></a>
How can I use a string value as a parameter?
public ActionResult Edit(string EditId)
{
if (Session["username"] != null)
{
int id;
//Check try to parse the string into an int if it fails it will return false if it was parsed it will return true
bool result = Int32.TryParse(EditId, out id);
if (result)
{
//I wouldn't use find unless you're 100% sure that record will always be there.
//This will return null if it cannot find your userinfo with that ID
UserInfo uinfo = db.UserInfoes.FirstOrDefault(x=>x.ID == id);
//Check for null userInfo
return View(uinfo);
}
else
{
return RedirectToAction("HomeIndex");
}
}
i have a dropdownlist getting data from data base
it contains 4 data :
my controller :
public ActionResult Index()
{
ViewBag.Postes = _db.Postes.ToList();
return View();
}
[HttpPost]
public ActionResult Index( Poste poste,string num_cin="R346399")
{
if (ModelState.IsValid)
{
if (poste.Id == 3)
{
return RedirectToAction("Inscription", "Candidat");
}
return View(poste);
}
}
my view
#Html.DropDownListFor(model => model.Id,
new SelectList(ViewBag.Postes, "Id", "intitule_poste"),"choisir le poste")
the problem that if i choose a value from dropdownlist that !=3 it's give me an error "that items must be not null "
You view includes #Html.DropDownListFor() which is generated based on the value of ViewBag.Postes. When you return the view (i.e. when poste.Id is not equal to 3) you must reassign the value of ViewBag.Postes
if (ModelState.IsValid)
{
if (poste.Id == 3)
{
return RedirectToAction("Inscription", "Candidat");
}
ViewBag.Poste = _db.Postes.ToList(); // reassign collection for dropdown
return View(poste);
}