Details asp.net mvc4 - asp.net-mvc

I'm trying to open the details of the "Ansatte" object. The problem is that the Int parameter is only null
I have this View
#model IEnumerable<EL4.Administrasjon.Models.Ansatte>
<table>
#foreach (var item in Model) {
<tr data-pkey="#item.IdBaksystem">
<td>
#Html.DisplayFor(modelItem => item.AnsNavn)
</td>
<td>
#Html.DisplayFor(modelItem => item.ePostAdresse)
</td>
<td class="rowControl hidden">
#Html.ActionLink("Details", "Details", new { id=item.ID_Ansatt }) |
</td>
</tr>
}
Then I have this in the controller
public class HMAnsatteController : Controller
{
//
// GET: /HMAnsatte/
public ActionResult Index()
{
HM_000_EL4Entities hmEnt = new HM_000_EL4Entities();
List<Ansatte> HMansatte = hmEnt.Ansatte.ToList();
return View(HMansatte);
}
public ActionResult Details(int? ansattNr)
{
if (ansattNr == null)
{
return null;
}
else
{
Entities ent = new Entities();
Ansatt el4Ansatt = ent.Ansatt.Where(a => a.AnsattNr == ansattNr).First();
return View(el4Ansatt);
}
}
}
When I click details, the URL looks correct: http://localhost:50009/HMansatte/Details/1
But the int ansattNr is always "null"

you have this ...
public ActionResult Details(int? ansattNr)
and it should be this because of the dynamic object you are passing in the link
public ActionResult Details(int? id)
or change this instead ...
#Html.ActionLink("Details", "Details", new { ansattNr=item.ID_Ansatt })

It the line where you are creating your action link, you are naming the parameter "id" but in your action method, you are calling it "ansattNr". Those names should be the same. Since the default routing is already set up for "id", I would just change the method signature of your action method to this:
public ActionResult Details(int? id)
That should solve the problem.

Your passing an variable with a name of id into the controller (which your global.asax has mapped to the URL so it shows like it does) but your controller is looking for a variable with name ansattNr.
You can either change the name of the variable in your controller to id or you can change your Action link to #Html.ActionLink("Details", "Details", new { ansattNr=item.ID_Ansatt }) but the second option will change the formatting on your URL.

Related

Display Active Directory Group in a MVC view

I Am trying to display active directory group member in the view. When i run the Code I am having the error "The model item passed into the dictionary is of type 'System.String[]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[SSSFT.LogIT.Models.ActiveDirectory]'". Debbuging the code show all the group member i am looking for
Model Class
public class ActiveDirectory
{
public int id { get; set; }
//public string Username { get; set; }
//public string Email { get; set; }
public string SamAccountName { get; set; }
}
Controller
public ActionResult Index(string username)
{
username = "sssftappdev";
string[]output = null;
using (var ctx = new PrincipalContext(ContextType.Domain))
using (var user = UserPrincipal.FindByIdentity(ctx, username))
{
if (user != null)
{
output = user.GetGroups() //this returns a collection of principal objects
.Select(x => x.SamAccountName) // select the name. you may change this to choose the display name or whatever you want
.ToArray(); // convert to string array
}
}
return View(output);
}
View
#model IEnumerable<SSSFT.LogIT.Models.ActiveDirectory>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.SamAccountName)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.SamAccountName)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.id }) |
#Html.ActionLink("Details", "Details", new { id=item.id }) |
#Html.ActionLink("Delete", "Delete", new { id=item.id })
</td>
</tr>
}
</table>
You can fix this error by simply updating your #model with:
#model String[]
You are currently passing a String[] to your view while expecting an IEnumerable of SSSFT.LogIT.Models.ActiveDirectory. Either update your code to return the right type of data, or adapt your strongly typed view with the actual result you return.

Passing data base info from controller to view in .NET MVC

Hello I'm trying to pass some database info from my controller to my view, but don't find the best way to do it. I'm populating the model in my controller, but I need to populate those values from database. I have a class called DataAccess which is the one that contains all my queries but not sure where I should put the logic to populate. I would say a for loop in my controller to populate the values, but seems to fail since I'm declaring the SchedulerViewModel there
The idea is having my values next to a radio button, so when selecting a radio button, I can "detect" the value and do something with that option....any suggestion would be appreciated...
My model:
public class SchedulerViewModel
{
public string theValue { get; set; }
public SelectListItem[] Items { get; set; }
}
My Controller:
public ActionResult Scheduler()
{
//DataAccess dataAccess = new DataAccess();
//for loop here???
var model = new SchedulerViewModel
{
Items = new[]
{
new SelectListItem { Value = "U", Text = "USA" }
}
};
return View(model);
}
My view:
#using (Html.BeginForm())
{
for (int i = 0; i < Model.Items.Count(); i++)
{
#Html.RadioButtonFor(x => x. theValue, Model.Items[i].Value, new { id = "item_" + i })
#Html.Label("item_" + i, Model.Items[i].Text)
<br />
}
}
Ideally you would have a service class that handles your database access. You shouldn't directly invoke the data layer from the controller, although nothing prevents you from doing it. For simplicity, I'm just putting calling the data access directly in the controller. The idea is that you need to return a collection of data, here an IEnumerable, in the View at the controller level so that the View can display this data.
Controller:
[HttpGet]
public ActionResult Index()
{
KnowledgeBaseEntities context = new KnowledgeBaseEntities();
IEnumerable<ISSUE> issues = context.ISSUES;
if(issues == null)
{
return HttpNotFound();
}
return View(issues);
}
View:
As you can see I'm referencing the collection of data that I'm expecting from the controller.
#model IEnumerable<ISSUE>
In this case it's an IEnumerable just like I had in the controller. Then you'll notice I'm referencing a Model object when I iterate the model.
#foreach (var item in Model)
Then I'm looping through each row of the model in order to add table rows to the table. Because we're using Model Binding from the Entity Framework. We're using Razor Syntax. You also notice I'm using Action Links for each row in the last column. This allows me to Edit, Delete or provide Details for a row of data. However, I will need to invoke another Controller Action for that. For example, you'd have an Edit controller action method that returns a single ISSUE to an Edit View.
#model IEnumerable<ISSUE>
#{
ViewBag.Title = "Knowledge Base Issues";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2 class="line">All Issues</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="flat">
<tr>
<th>#Html.DisplayNameFor(model => model.KEYWORDS)</th>
<th>#Html.DisplayNameFor(model => model.SUBJECT)</th>
<th>#Html.DisplayNameFor(model => model.DATE_ENTERED)</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>#Html.DisplayFor(modelItem => item.KEYWORDS)</td>
<td>#Html.DisplayFor(modelItem => item.SUBJECT)</td>
<td>#Html.DisplayFor(modelItem => item.DATE_ENTERED)</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ISSUE_ID }) |
#Html.ActionLink("Details", "Details", new { id=item.ISSUE_ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ISSUE_ID })
</td>
</tr>
}

Getting null value instead of Id from View to Edit action method

Getting 'null' from List View to Edit/Details/Delete Action method instead of the Id.
In List view, in Id column it shows corresponding Id without any issues. In All.cshtml file,
<td>
#Html.DisplayFor(modelItem => item.ModifiedOn)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.CategoryId }) |
#Html.ActionLink("Details", "Details", new { id = item.CategoryId }) |
#Html.ActionLink("Delete", "Delete", new { id = item.CategoryId })
</td>
And Edit method is,
public ActionResult Edit(int? id) {
if (id == null) {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return View();
}
var editCategory = new PetaPoco.Database("DefaultConnection");
var category = editCategory.Single<CategoryViewModels>("SELECT * FROM Category WHERE
CategoryId=#0 AND IsActive = 1", id);
return View(category);
}
The Url in the browser is, /Category/Edit/C1. But in Edit/Details/Delete, the Id is null.
What am I missing?
Thanks.
Since the url can be /Category/Edit/C1, the id parameter in the controller action method can't be an int?. Try to change the type of id to string
public ActionResult Edit(string id) {
if (string.IsNullOrEmpty(id)) {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return View();
}
var editCategory = new PetaPoco.Database("DefaultConnection");
var category = editCategory.Single<CategoryViewModels>("SELECT * FROM Category WHERE
CategoryId=#0 AND IsActive = 1", id);
return View(category);
}
the "C1" is not type of int, convert it to "int?" will get null.

ViewModel not posting back

I have this in my controller:
public ActionResult Index()
{
var viewModels = _dataSyncService.Get().Select(provider => new IndexViewModel
{
Selected = false, Provider = provider
}).ToList();
return View(viewModels);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(IEnumerable<IndexViewModel> viewModels)
{
//Breakpoint on this to check viewModels
}
ViewModel:
public class IndexViewModel
{
public bool Selected { get; set; }
public IDataSyncProvider Provider { get; set; }
}
And my Index.cshtml:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<button type="submit" class="btn blue">Trigger Selected</button>
#foreach (var sync in Model)
{
<tr>
<td>
#Html.CheckBoxFor(s => sync.Selected)
</td>
<td>#sync.Provider.FriendlyName</td>
</tr>
}
}
But my models are posted back, viewModels always comes back as null. I read alot about having to assign Id's to the check box etc but I thought that's what Html.CheckBoxFor is for.
I'm sure I'll be kicking myself about this at some point but I could do with some guidance please.
If you want to use the built in Html helpers like Html.CheckBoxFor then you need to use a for loop instead of the foreach in order to the helpers render the correct input names:
#for(int sync = 0; sync < Model.Count; sync++)
{
<tr>
<td>
#Html.CheckBoxFor(m => Model[sync].Selected)
</td>
<td>#Model[sync].Provider.FriendlyName</td>
</tr>
}
You can read more about binding to lists here: Model Binding To A List
This is because, you are just redirecting it using return RedirectToAction("Index");
In your POST action
try :
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(IEnumerable<IndexViewModel> viewModels)
{
return View(viewModels);
}
Hope will help.

How to insert a record in MVC4?

How to insert a record in MVC4 with Entity Framework?
here is my viewpage:
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.brand_id)
</td>
<td>
#Html.DisplayFor(modelItem => item.brand_name)
</td>
<td>
#Html.ActionLink("ADD", "BrandList", new { item.brand_id })
</td>
</tr>
}
here is my controller code:
public ActionResult BrandList()
{
return View(db.brand.ToList());
}
[HttpPost]
public ActionResult BrandList(int id)
{
lovelist Add_Brand = new lovelist();
Add_Brand.lovelist_member = (int)Session["Member_ID"];
Add_Brand.lovelist_brand = id;
db.lovelist.Add(Add_Brand);
db.SaveChanges();
return RedirectToAction("BrandList");
}
This is what I did so far.
I cannot insert a record to my DB.
There's no any error message. I still cannt insert a record to my DB.
You have 2 actions on your controller called BrandList. The second is decorated with the [HttpPost] attribute meaning that it can only be invoked using the POST verb. But in the code you have shown you have only a hyperlink:
#Html.ActionLink("ADD", "BrandList", new { item.brand_id })
In HTML a hyperlink (anchor) sends GET request. So basically when you click on this link you are invoking the first action which doesn't do any DB saving. If you wanted to invoke the second action using a hyperlink you should rename it (because you cannot have 2 actions with the same name accessible with the same verb) and remove the [HttpPost] attribute from it:
public ActionResult SaveBrandList(int id)
{
lovelist Add_Brand = new lovelist();
Add_Brand.lovelist_member = (int)Session["Member_ID"];
Add_Brand.lovelist_brand = id;
db.lovelist.Add(Add_Brand);
db.SaveChanges();
return RedirectToAction("BrandList");
}
You will obviously need to adapt your view as well:
#Html.ActionLink("ADD", "SaveBrandList", new { item.brand_id })
There's also a possibility to use an AJAX link which would allow you to send a POST request:
#Ajax.ActionLink("ADD", "BrandList", new { item.brand_id }, new AjaxOptions { HttpMethod = "POST" })
You will need to include the jquery.unobtrusive-ajax.js script in your view for this to work. Also since you are using an AJAX call now, there's no need to be redirecting anymore from your POST controller action but simply return some partial view or JSON that could be used on the client to refresh some portion of the page.
You have missed parameter name in id and controllername . please change your action-link to
#Html.ActionLink("ADD", "BrandList","ControllerName", new {id = item.brand_id })

Resources