my search button goes to the wrong function - c#

My Get function works fine and the search textbox shows but when I enter the user ID and click search, it goes directly to the post function. It is supposed to go to the Get function again to show the data . after the data shows and whether I selected from the checkboxes or not, I click save and then it is supposed to go to the POst function.
What am I doing wrong?
GET function :
[HttpGet]
public ActionResult Index(int? SearchId)
{
var viewModel = new UserViewModel();
if (SearchId != null)
{
var userDepartments = db.TBL_User_Dep_Access.Where(x => x.UserID == SearchId).Select(x => x.Dep_ID).ToList();
List<UserDepartmentViewModel> udeptVM = db.TBL_Department.Select(i => new UserDepartmentViewModel
{
Dep_Id = i.Department_ID,
Dep_Name = i.Department_Name,
IsChecked_ = userDepartments.Contains(i.Department_ID)
}).ToList();
var userPermissions = db.TBL_UserPermissions.Where(x => x.UserID == SearchId).Select(m => m.PermissionID).ToList();
List<UsrPERViewModel> upVM = db.TBL_Permissions.Select(i => new UsrPERViewModel
{
Id = i.PermissionID,
Name = i.PermissionName,
IsChecked = userPermissions.Contains(i.PermissionID)
}).ToList();
viewModel.Departments = udeptVM;
viewModel.Permissions = upVM;
}
return View(viewModel);
}
My View:
#model Staff_Requisition.Models.UserViewModel
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<style>
.list-group {
max-height: 300px;
margin-bottom: 10px;
overflow: scroll;
-webkit-overflow-scrolling: touch;
}
</style>
#using (Html.BeginForm("Index", "TBL_UserPermission"))
{
#Html.AntiForgeryToken()
<body class="nav-md">
<div class="container body">
<div class="main_container">
<div class="title_right">
<div class="col-md-5 col-sm-5 col-xs-12 form-group pull-right top_search">
<div class="input-group">
#Html.TextBox("SearchId", "", null, new { #id = "SearchId", #placeholder = "Search for...", #class = "form-control" })
<span class="input-group-btn">
<input class="btn btn-default" value="Search" type="submit">Go! />
</span>
<ul>
#if (Model.Permissions != null)
{
foreach (var P in Model.Permissions)
{
<li>
<p>
#Html.CheckBoxFor(modelItem => P.IsChecked, new { #class = "flat", #value = P.IsChecked })
#Html.DisplayFor(modelItem => P.Name, new { #class = "DepartmentName", #value = P.Name })
#Html.HiddenFor(modelItem => P.Id, new { #class = "Dep_Id", #value = P.Id })
</p>
</li>
}
}
</ul>
<ul class="to_do">
#if (Model.Departments != null)
{
foreach (var D in Model.Departments)
{
<li>
<p>
#Html.CheckBoxFor(modelItem => D.IsChecked_, new { #class = "flat", #value = D.IsChecked_ })
#Html.DisplayFor(modelItem => D.Dep_Name, new { #class = "DepartmentName", #value = D.Dep_Name })
#Html.HiddenFor(modelItem => D.Dep_Id, new { #class = "Dep_Id", #value = D.Dep_Id })
</p>
</li>
}
}
</ul>
<div class="col-xs-12 col-sm-6 emphasis">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</body>
}
My POST function:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(UserViewModel user_Pers)
{
//remove user with specified ID from database
db.TBL_UserPermissions.RemoveRange(db.TBL_UserPermissions.Where(c => c.UserID == user_Pers.SearchId));
db.TBL_User_Dep_Access.RemoveRange(db.TBL_User_Dep_Access.Where(c => c.UserID == user_Pers.SearchId));
//for each permission that's checked add user to the table
foreach (var u in user_Pers.Permissions)
{
if (u.IsChecked)
{
TBL_UserPermissions Tup = new TBL_UserPermissions();
Tup.UserID = user_Pers.SearchId;
Tup.PermissionID = u.Id;
Tup.IsActive = true;
db.TBL_UserPermissions.Add(Tup);
}
}
db.SaveChanges();
foreach (var d in user_Pers.Departments)
{
if (d.IsChecked_)
{
TBL_User_Dep_Access Tud = new TBL_User_Dep_Access();
Tud.UserID = user_Pers.SearchId;
Tud.Dep_ID = d.Dep_Id;
Tud.IsActive = true;
db.TBL_User_Dep_Access.Add(Tud);
}
}
db.SaveChanges();
return RedirectToAction("myInfo");
}
BTW I removed most of the div in the view manually for simplicity, so it's okay if an opening or closing doesn't match.

As has been pointed out in the comments, in your code you have 1 form whereas to solve the problem you are talking about you need 2 forms. One form responsible for the search get request and the other responsible for the user post.
Here is a simple example of a search form and an update form on the same page.
The viewmodel and controller
using System.Web.Mvc;
namespace SearchAndSubmit.Controllers
{
public class UserViewModel
{
public int? Id { get; set; }
public string Name { get; set; }
}
public class HomeController : Controller
{
[HttpGet]
public ActionResult Edit(int? SearchId)
{
var viewModel = new UserViewModel();
if (SearchId != null)
{
viewModel.Id = SearchId;
//logic to search for user and create viewmodel goes here
}
return View(viewModel);
}
[ValidateAntiForgeryToken]
[HttpPost]
public ActionResult Edit(UserViewModel user_Pers)
{
//validation and create update logic goes here
return RedirectToAction("Index");
}
}
}
The view
#model SearchAndSubmit.Controllers.UserViewModel
#{
ViewBag.Title = "Edit/create user";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>#ViewBag.Title</h2>
#*This is the search form it does a get request*#
#using (Html.BeginForm("edit", "home", FormMethod.Get))
{
#Html.TextBox("SearchId", "", null, new { #id = "SearchId", #placeholder = "Search for...", #class = "form-control" })
<span>
<input value="Search" type="submit">
</span>
}
#*This is the form for updating the user it does a post*#
#using (Html.BeginForm("edit", "home", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(c => c.Id)
<p>
#Html.LabelFor(c => c.Name)
#Html.TextBoxFor(c => c.Name)
</p>
<div>
<input type="submit" value="Save" />
</div>
}

Related

Getting 404 Error MVC when trying to add New Object to a List

I have Friend view where are my Friends are listed inside a table as show in the picture below.
Now I have added new feature Add Friend so when I click on the the Link I am getting:
The resource cannot be found. HTTP 404
Here is my View where all friends are listed:
#using Lab3.Models
#model IEnumerable<Lab3.Models.FriendModel>
#{
ViewBag.Title = "Friends";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Friends</h2>
#Html.ActionLink("Add Friend", "AddNewFriend", "Friend", null, new { #class = "btn btn-primary" })
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Friend Id</th>
<th>Friend Name</th>
<th>Place</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (FriendModel friend in Model)
{
<tr>
<td>#friend.Id</td>
<td>#friend.Ime</td>
<td>#friend.MestoZiveenje</td>
<td>
#Html.ActionLink("Edit", "EditFriend", new { id = friend.Id }, null)
</td>
</tr>
}
</tbody>
</table>
The AddFriend view:
#model Lab3.Models.FriendModel
#{
ViewBag.Title = "AddFriend";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>AddFriend</h2>
#using (Html.BeginForm("AddNewFriend","Friend"))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>FriendModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Ime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Ime, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Ime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MestoZiveenje, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MestoZiveenje, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MestoZiveenje, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
And my the FriendController:
using Lab3.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Lab3.Controllers
{
public class FriendController : Controller
{
private static List<FriendModel> friendModels;
// GET: Friend
public ViewResult Index()
{
var friends = GetFriends();
return View(friends);
}
public ViewResult EditFriend(byte id)
{
var friend = GetFriends().SingleOrDefault(f => f.Id == id);
return View("EditFriend",friend);
}
[HttpPost]
public ActionResult AddNewFriend(FriendModel friend)
{
friendModels.Add(friend);
return View("Index", friendModels);
}
private IEnumerable<FriendModel> GetFriends()
{
return new List<FriendModel>
{
new FriendModel {Id = 1, Ime = "Marry", MestoZiveenje = "Dubai"},
new FriendModel {Id = 2, Ime = "John", MestoZiveenje = "London"},
new FriendModel {Id = 3, Ime = "Smith", MestoZiveenje = "Manchester"}
};
}
}
}
Why I am getting this 404 Error Page not found ?
The problem is that there is no action for your AddNewFriend View to redirect, a view should have a action with method get to redirect, and post methods are for once you submit the form in your view
Add below method in your controller it should solve the issue
[HttpGet]
public ActionResult AddNewFriend()
{
return View();
}
Error 404 means it can't find a route from your URL.
Check this line in your Razor page
#Html.ActionLink("Edit", "EditFriend", new { id = friend.Id }, null)
Here you are telling, When I click the link, Goto controller:"Edit" & action:"EditFriend".
This will resolve to "https://localhost/Edit/EditFriend?id=1"
But I can't find a EditController here and thus this link creates 404
Try putting "Friend" here because we have a "FriendController". Like
#Html.ActionLink("Friend", "EditFriend", new { id = friend.Id }, null)
This will resolve to "https://localhost/Friend/EditFriend?id=1"

Pass data between several views in MVC applications

I am creating a MVC application and I would like to pass data between views.
Here is my first view:
#model ClassDeclarationsThsesis.Models.AddGroupViewModel
#{
ViewBag.Title = "Add Groups";
}
<h2>Add Groups to subjects</h2>
#foreach (var user in Model.Users)
{
if (user.email.Replace(" ", String.Empty) == HttpContext.Current.User.Identity.Name)
{
if (user.user_type.Replace(" ", String.Empty) == 3.ToString() || user.user_type.Replace(" ", String.Empty) == 2.ToString())
{
using (Html.BeginForm("AddGroup", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Create new groups.</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#{
List<SelectListItem> listItems1 = new List<SelectListItem>();
}
#foreach (var subject in Model.Subjects)
{
listItems1.Add(new SelectListItem
{
Text = subject.name,
Value = subject.name,
Selected = true
});
}
#Html.LabelFor(m => m.subject_name, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.subject_name, listItems1, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.qty, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.qty, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Submit" />
</div>
</div>
}
}
if (user.user_type.Replace(" ", String.Empty) == 1.ToString())
{
<p>You do not have enough permissions to enter this page. Contact the administrator.</p>
}
}
}
And my controller for this:
public ActionResult AddGroup(AddGroupViewModel model)
{
var entities = new ClassDeclarationsDBEntities1();
var model1 = new AddGroupViewModel();
model1.Subjects = entities.Subjects.ToList();
model1.Users = entities.Users.ToList();
// set your other properties too?
if (ModelState.IsValid)
{
return RedirectToAction("AddGroupsQty", "Account");
}
return View(model1);
}
And what I would like to achieve is to pass chosen item from dropdown list and this qty variable to AddGroupsQty View. How do I do this? In my controller of AddGroupsQty i have just a simple return of view so far.
You can pass the values using querystring.
return RedirectToAction("AddGroupsQty", "Account",
new { qty=model.qty,subject=model.subject_name);
Assuming your AddGroupsQty have 2 parameters to accept the quantity and subject
public ActionResult AddGroupsQty(int qty,string subject)
{
// do something with the parameter
// to do : return something
}
This will make browser to issue a new GET request with the values in query string. If you do not prefer to do that, you can use a server side temporary persistence mecahnism like TempData
TempData["qty"]=model.qty;
TempData["subject"]= model.subject_name;
return RedirectToAction("AddGroupsQty", "Account");
And in your AddGroupsQty action,
public ActionResult AddGroupsQty()
{
int qty=0;
string subjectName=string.Empty;
if(TempData["qty"]!=null)
{
qty = Convert.ToInt32(TempData["qty"]);
}
if(TempData["subject"]!=null)
{
subjectName = TempData["subject"];
}
// Use this as needed
return View();
}
If you want to pass these values from the ADdGroupsQty action to it's view, you can use either a view model or ViewBag/ViewData.

MVC dropdownlist wrong display

I am maing an MVC application connected to Entity Framework. In my view I have a dropdown list. Code looks like this:
#{
ViewBag.Title = "ClassesPickGroup"; } #model ClassDeclarationsThsesis.Models.ClassesPickGroupViewModel
<h2>ClassesPickGroup</h2>
#foreach (var user in Model.users) {
if (user.email.Replace(" ", String.Empty) == HttpContext.Current.User.Identity.Name)
{
if (user.user_type.Replace(" ", String.Empty) == 3.ToString() || user.user_type.Replace(" ", String.Empty) == 2.ToString())
{
using (Html.BeginForm("ClassesPickGroup", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Generate summary views</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#{
List<SelectListItem> listItems1 = new List<SelectListItem>();
foreach (var sub in Model.subjects)
{
if (sub.name.Replace(" ", String.Empty) == Model.subject_name.Replace(" ", String.Empty))
{
Model.subject_id = sub.class_id;
}
}
foreach (var group in Model.groups)
{
if (group.class_id == Model.subject_id)
{
listItems1.Add(new SelectListItem
{
Text = group.name,
Value = group.name,
});
}
}
}
#Html.LabelFor(m => m.selected_group, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.selected_group, listItems1, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Submit" />
</div>
</div>
}
}
if (user.user_type.Replace(" ", String.Empty) == 1.ToString())
{
<p>You do not have enough permissions to enter this page. Contact the administrator.</p>
}
}
}
However, in my dropdown list I see wrong things. The number of elements is correct, but all the names are the same, all the names correspond to first matching 'group' to pick from model. What do I do wrong?
My controller looks like this:
public ActionResult ClassesPickGroup(ClassesPickGroupViewModel value)
{
ClassDeclarationsDBEntities1 entities=new ClassDeclarationsDBEntities1();
int subj_id=0;
ClassesPickGroupViewModel model=new ClassesPickGroupViewModel();
model.subject_name = value.subject_name;
foreach (var subject in entities.Subjects)
{
if(subject.name.Replace(" ",String.Empty)==value.subject_name.Replace(" ", String.Empty))
{
subj_id = subject.class_id;
}
}
model.groups = entities.Groups.ToList();
model.subjects = entities.Subjects.ToList();
model.users = entities.Users.ToList();
if (ModelState.IsValid)
{
return RedirectToAction("ClassesView", "Account");
}
else
{
model.groups = entities.Groups.ToList();
model.subjects = entities.Subjects.ToList();
model.users = entities.Users.ToList();
return View(model);
}
return View(model);
}
Apparently, adding groups does not work well, groups are not unique (however in database they are). What is wrong with it?
You are not passing any value for model.subject_id from controller. That is why the last value is kept saved for taking names it only hits the same subject_id
#{
ViewBag.Title = "ClassesPickGroup"; } #model ClassDeclarationsThsesis.Models.ClassesPickGroupViewModel
<h2>ClassesPickGroup</h2>
#foreach (var user in Model.users) {
if (user.email.Replace(" ", String.Empty) == HttpContext.Current.User.Identity.Name)
{
if (user.user_type.Replace(" ", String.Empty) == 3.ToString() || user.user_type.Replace(" ", String.Empty) == 2.ToString())
{
using (Html.BeginForm("ClassesPickGroup", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Generate summary views</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#{
List<SelectListItem> listItems1 = new List<SelectListItem>();
foreach (var sub in Model.subjects)
{
if (sub.name.Replace(" ", String.Empty) == Model.subject_name.Replace(" ", String.Empty))
{
Model.subject_id = sub.class_id;
}
foreach (var group in Model.groups)
{
if (group.class_id == Model.subject_id)
{
listItems1.Add(new SelectListItem
{
Text = group.name,
Value = group.name,
});
}
}
}
}
}
#Html.LabelFor(m => m.selected_group, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.selected_group, listItems1, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Submit" />
</div>
</div>
}
}
if (user.user_type.Replace(" ", String.Empty) == 1.ToString())
{
<p>You do not have enough permissions to enter this page. Contact the administrator.</p>
}
}
}

Why isn't my drop down value being submitted to the action?

I have a DropDownListFor on my view. In fact I have 3, out of three of them only two of them work. Despite being almost exactly the same code, my get around at the moment is to create an input box and populate it on click of a button with the value from the drop down box(strange I know, I can get the value using JQuery). I've checked and all names seem to be the same so I'm really not sure why it doesn't submit.
View:
<content id="GenerateReportContent" class="col-lg-4 col-md-4 col-sm-12 col-xs-12">
#using (Html.BeginForm("ReportSelection", "Search", FormMethod.Post, new { #id = "GenerateReportContainer" })) {
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="AltFunctions">
<ul>
<li>
<a href="javascript:document.getElementById('GenerateReportContainer').reset();" class="AltButton" id="altClearButton" title="Reset the 'Generate Report' container" >Clear</a>
</li>
<li>
Info
</li>
</ul>
</div>
<h1 id="GenerateReportHeader">SEARCH ENGINE</h1>
</div>
<input type="hidden" name="ClientID" value="#Model.ClientID" id="Client" />
<input type="hidden" name="ClientName" value="#Model.ClientName" id="ClientName" />
<input type="hidden" name="SupplierFound" value="#Model.SupplierFound" id="SupplierFound" />
#Html.TextBoxFor(m => m.ClaimNo, "", new { #id = "txtGRCSelect", #class = "form-control", placeholder = "Enter Specific Claim Number..." })
<br />
<div class="ui-widget">
#Html.TextBox("SupplierAuto", "", new { #id = "SupplierAutotxt", #class = "form-control SupplierAutoComplete", placeholder = "Search for a supplier name" })
</div>
#Html.DropDownListFor(m => m.SupplierID, new SelectList(Model.Suppliers, "SupplierID", "DisplayName"), "Select Supplier Name", new { #id = "SuppNameDD", #class = "GRDropDown"})
<br />
<!-- THE DROP DOWN IN QUESTION-->
#Html.DropDownListFor(m => m.GroupModelClass.GroupID, new SelectList(Model.GroupModelClass.ClaimGroups, "GroupID", "GroupName"), "Select Supplier Group Name", new { #id = "SuppGroupDD", #class = "GRDropDown" })
<br />
#Html.DropDownListFor(m => m.ReviewPeriodID, new SelectList(Model.ReviewPeriods, "ReviewPeriodID", "ReviewPeriodName"), "Select Review Period", new { #id = "ReviewPeriodDD", #class = "GRDropDown" })
// Have to submit this field at the moment as the drop down value is not being submitted
<input hidden id="GroupIDInput" name="GroupIDInput" />
<br />
<br />
<button type="submit" value="Submit" id="GenerateReportButton" class="btn btn-default">GO</button>
<div id="ErrorBox" hidden>
<div class="alert alert-danger" role="alert">
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span class="sr-only">Error:</span>
<p id="ErrorBoxText"></p>
</div>
</div>
}
</content>
Controller:
public ActionResult ReportSelection(int ClientID, string ClaimNo, string SupplierAuto, int? SupplierID = null, int? ReviewPeriodID = null, int? GroupID = null) {
if (SupplierAuto != "") {
var Suppliers = suppRepo.GetAllSuppliersByClientWithClaims(ClientID);
foreach (var item in Suppliers) {
if (item.DisplayName == SupplierAuto) {
SupplierID = item.SupplierID;
break;
}
}
if (SupplierID == null) {
return RedirectToAction("Index", "Dashboard", new { ClientID = ClientID });
}
}
client = clientRepo.GetClientNameByID(ClientID);
if (SupplierID != null || ReviewPeriodID != null || GroupIDInput != null) {
return RedirectToAction("SupplierReportSelection", new { ClientID = ClientID, SupplierID = SupplierID, ReviewPeriodID = ReviewPeriodID, ClaimIDs = ClaimIDs });
}
else {
return RedirectToAction("ClaimNumberReportSelection", new { ClientID = ClientID, ClaimNo = ClaimNo });
}
}
Anyone know why it doesn't work?
Use FormCollection:
[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV,FormCollection form)
{
string strDDLValue = form["<your-dropdown-name>"].ToString();
return View(MV);
}
If you want with Model binding then add a property in Model:
public class MobileViewModel
{
public List<tbInsertMobile> MobileList;
public SelectList Vendor { get; set; }
public string SelectedVender {get;set;}
}
and in View:
#Html.DropDownListFor(m=>m.SelectedVender , Model.Vendor, "Select Manufacurer")
and in Action:
[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV)
{
string SelectedValue = MV.SelectedVendor;
return View(MV);
}
Check with fiddler or F12, but I'm betting m.GroupModelClass.GroupID is getting passed to the model binder as simply GroupID and it has no idea that it's supposed to map to GroupModelClass.GroupID. Try flattening your model a bit?

populate checkboxes from database

I want to show a list of climbs, and the user can then select the climbs.
I do it like this:
public ActionResult GetClimbs(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
UserProfile user = db.userProfiles
.Include(i => i.Climbs)
.Where(i => i.Id == id)
.Single();
PopulateAssignedClimbData(user);
if (user == null)
{
return HttpNotFound();
}
return View(user);
}
private void PopulateAssignedClimbData(UserProfile user)
{
var allClimbs = db.Climbs;
var userClimbs = new HashSet<int>(user.Climbs.Select(c => c.climbID));
var viewModel = new List<AssignedClimb>();
foreach (var climb in allClimbs)
{
viewModel.Add(new AssignedClimb
{
ClimbID = climb.climbID,
Title = climb.Name,
Assigned = userClimbs.Contains(climb.climbID)
});
}
ViewBag.Climbs = viewModel;
}
and for the view I have this:
#model ContosoUniversity.Models.UserProfile
#using ContosoUniversity.Source
#{
ViewBag.Title = "Edit";
}
#using (Html.BeginForm("GetClimbs", "Account", FormMethod.Post, new { id = "form_Id", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.HiddenFor(model => model.Id)
<table>
<tr>
#{
int cnt = 0;
List<ContosoUniversity.ViewModels.AssignedClimb> climbs = ViewBag.Climbs;
foreach (var climb in climbs)
{
if (cnt++ % 3 == 0)
{
#:</tr><tr>
}
#:<td>
<input type="checkbox"
name="selectedClimbs"
value="#climb.ClimbID"
#(Html.Raw(climb.Assigned ? "checked=\"checked\"" : ""))/>
#climb.ClimbID #: #climb.Title
#:</td>
}
#:</tr>
}
</table>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
But every time I get the message by this line:
foreach (var climb in climbs)
that climbs is null although I have some climbs in the database.
It also doesn't enter the GetClimbs method in the controller.
So the view is a tab, but how to trigger from the tab the action method: PopulateAssignedClimbData(user); this method is in the Account Controller
Thank you
this is my edit with all the tabs:
<div id="tabs">
<ul>
<li>Personal information</li>
<li>Profile Photo</li>
<li>Other Photos</li>
<li>Climbs</li>
</ul>
<div id="tabs-1">
#Html.Partial("_GetUserProfile", Model)
</div>
<div id="tabs-2">
#Html.Partial("_GetProfilePicture", Model)
</div>
<div id="tabs-3">
#Html.Partial("_GetOtherImages", Model)
</div>
<div id="tabs-4">
#Html.Partial("_GetClimbTab", Model)
</div>
</div>
this is doing the job:
$.get('#Url.Action("PopulateAssignedClimbData", "Account", new { id = Model.Id })', function (data) {
$('#_GetClimbTab').html(data);
});

Categories