in mvc the view is not receiving a list while the controller class is sending it correctly - asp.net-mvc-4

I am sending a list from controller to view but the view is not receiving it despite the list being populated in the controller
Controller:
public class DepartmentController : Controller
{
// GET: Department
public ActionResult Index() {
EmployeeContext employeeContext = new EmployeeContext();
List<Department> departments =
employeeContext.Departments.ToList();
return View();
}
}
View:
#model IEnumerable<MVCDemo.Models.Department>
#using MVCDemo.Models;
#{
ViewBag.Title = "Departments List";
}
<div style="font-family:Arial">
<h2>Departments List</h2>
<ul>
#foreach (Department Department in #model) {
<li>#Html.ActionLink(Department.name, "Index","Employee", new {
departmentid = Department.ID })</li>
}
</ul>
</div>

public class DepartmentController : Controller{
// GET: Department
public ActionResult Index() {
EmployeeContext employeeContext = new EmployeeContext();
List<Department> departments =
employeeContext.Departments.ToList();
return View(departments);
}}

Related

Where i must get Ajax Helper or how to create it to use #AjaxExtensions.ActionLink

I want to use #AjaxExtensions.ActionLink(AjaxHelper, String, String, String, RouteValueDictionary, AjaxOptions) in cshtml file (ASP.Net 6 MVC).
#model List<Shift>
#using System.Web.Mvc.Ajax;
#{
AjaxOptions deleteOptions = new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "table"
};
}
#foreach (Shift shift in Model)
{<td>
#AjaxExtensions.ActionLink( ???,"Delete", "DeleteShift", "MainDoctor", new{id=shift.Id}, deleteOptions)
</td>
}
As this document said, AjaxExtensions.ActionLink is only applies to ASP.NET MVC 5.2, and the correct usage should be:
#Ajax.ActionLink("Delete", "DeleteShift", "MainDoctor", new { id = shift.Id }, deleteOptions)
In ASP.NET 6, you need use an alternative way like below:
<a data-ajax="true" data-ajax-mode="replace" data-ajax-update="#table" data-ajax-url="#Url.Action("DeleteShift", "MainDoctor", new { id = shift.Id})">Delete</a>
A simple working demo you could follow:
Model:
public class Test
{
public string Id{ get; set; }
}
View(Views/Home/Index.cshtml):
#model Test
<div id="table">
#Model.Id
<a data-ajax="true" data-ajax-mode="replace" data-ajax-update="#table" data-ajax-url="#Url.Action("DeleteShift", "MainDoctor", new { id = 1 })">Delete</a>
</div>
#section Scripts
{
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ajax-unobtrusive/3.2.6/jquery.unobtrusive-ajax.js" integrity="sha256-v2nySZafnswY87um3ymbg7p9f766IQspC5oqaqZVX2c=" crossorigin="anonymous"></script>
}
Controller:
public class MainDoctorController:Controller
{
public IActionResult DeleteShift(int id)
{
var model = new Test()
{
Id = "bb"
};
return PartialView("/Views/Home/Index.cshtml", model);
}
}
public class HomeController : Controller
{
public async Task<IActionResult> Index()
{
var model = new Test()
{
Id = "aaa"
};
return View(model);
}
}
Result:

Deleting User in SQL Server

I'm trying to create an admin area where the admin can delete a user from dbo.AspNetUsers. So far I have this in my index view from my admin controller:
#using BlogMaxim.Models
#model List<BlogMaxim.Models.Users>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#foreach (Users user in Model)
{
<div class="table-responsive">
<table class="table table-condensed">
<tr>
<th>Username</th>
<th>Email</th>
<th>Id</th>
</tr>
<tr>
<td>#user.UserName</td>
<td>#user.Email</td>
<td>#user.Id</td>
<td>#using (Html.BeginForm("Delete", "Admin", new { id = user.Id }))
{
<input type="submit" class="button" value="Delete" />
}</td>
</tr>
</table>
</div>
}
It shows all the users along with a delete button next to it. I do not know what code I need to write in my admincontroller's Delete method:
public class AdminController : Controller
{
private UserRepository repoUsers = new UserRepository();
// GET: Admin
[Authorize(Roles = "Admin")]
public ActionResult Index()
{
List<Users> users = repoUsers.GetUsers();
return View(users);
}
public ActionResult Delete()
{
return RedirectToAction("Index");
}
}
This is what I have at this time, I'm rather new to ASP.NET MVC.
If you are using EF then its more simpler as:
[HttpPost]
public ActionResult Delete(int Id)
{
private ApplicationDbContext context = new ApplicationDbContext();
var user = context.Users.Find(Id);
context.Users.Remove(user);
context.SaveChanges();
return RedirectToAction("Index");
}
where ApplicationDbContext is the child class of IdentityDbContext placed in IdentityModels.cs in Models folder
Create a dbEntities class-
public partial class dbEntities : DbContext
{
public dbEntities()
: base("name=the name of the database that you have given in connectionstring")
{
}
}
In the controller -
private readonly dbEntities database;
public AdminController ()
{
this.database = new dbEntities();
}
Then in your ActionResult of Delete
public ActionResult Delete(int Id)
{
ABC abc = new ABC();
abc = db.ABC.Find(Id);
database.Remove(abc);
database.SaveChanges();
return RedirectToAction("Index");
}

multiple ajax forms in the same mvc 4 view doesn't work properly - after the second time of submit my model is empty

I've got a class Cart with property Lines which returns me a collection of type CartLine. here is my two classes Cart ad CartLine
public class Cart
{
private List<CartLine> lineCollection = new List<CartLine>();
public String Currency { get; set; }
public void UpdateCart(int ArticleID, string selectedQuantityType, int Quantity)
{
CartLine line = lineCollection.Where(p => p.Product.ArticleID == ArticleID).FirstOrDefault();
if (line != null)
{
line.SelectedQuantityType = selectedQuantityType;
line.Quantity = Quantity;
}
}
public IEnumerable<CartLine> Lines
{
get { return lineCollection; }
}
}
<
And here is my class CartLine
public class CartLine
{
public CartLine()
{
this.QuantityType= new List<QuantityType>();
}
public WebServiceBeaMenu Product { get; set; }
public int Quantity { get; set; }
public string Currency { get; set; }
public string SelectedQuantityType { get; set; }
}
I've got two actions which returns me strongly typed PartialView - CartIndexViewModel with two properties - one from Type Cart
public ActionResult CartPartial(string returnUrl)
{
return PartialView(new CartIndexViewModel
{
Cart = GetCart(),
ReturnUrl = returnUrl
});
}
[HttpPost]
public ActionResult CartPartial(CartLine line)
{
Cart crt = GetCart();
crt.UpdateCart(line.Product.ArticleID, line.SelectedQuantityType, line.Quantity);
return PartialView(new CartIndexViewModel
{
Cart = crt
});
}
private Cart GetCart()
{
Cart cart = (Cart)Session["Cart"];
if (cart == null)
{
cart = new Cart();
Session["Cart"] = cart;
}
return cart;
}
ANd here is my view whih loop through all thre cartlines of my cart and display their quantity and quantityType.
The problem is as you see for each CartLine I'm making an ajax form so when there is a change in the quantity of a CartLine (when there is a change in this helper #Html.TextBoxFor(x => line.Quantity,new { id = #liine.Product.ArticleID, onchange="SubmitForm(this.id)" })) you see that I submit the form to the httppost form of my CartPartial Action. The first time when I submit the form there is no problem and thanks to mvc model binding my CartLine parameter is filled with the data I need. The problem is when this action returns me the same view with the updated data after that if I try to change a quantity and submit the form for the second time my CartLine parameter is empty. What may be the reason. Thankls in advance.
#model MvcBeaWeb.Models.CartIndexViewModel
<div id="cartContainer">
<table width="100%" align="center" style="margin:auto;border-collapse:collapse;">
<tbody>
#foreach(var line in Model.Cart.Lines)
{
<tr style="height:90px" >
#using (Ajax.BeginForm("CartPartial", null, new AjaxOptions { UpdateTargetId = "centerCartBody", InsertionMode = InsertionMode.Replace }, new { id = "form" + #line.Product.ArticleID }))
{
<td align="left">#line.Product.SpecialWord</td>
<td >
<div class="inner-content">
#Html.TextBoxFor(x => line.Quantity,new { id = #liine.Product.ArticleID, onchange="SubmitForm(this.id)" })
<span class="qty-type">
#Html.DropDownListFor(x => line.SelectedQuantityType, new SelectList(line.QuantityType, "QuantityID", "Description"))
</span>
</div>
</td>
#Html.HiddenFor(x => line.Product.ArticleID, "Value");
}
</tr>
}
</tbody>
</table>
<div >
#using (Html.BeginForm("Index/","Confirmation"))
{
<input type="submit" id="btnCheckOut" />
}
</div>
</div>
</div>
</div>
script>
function SubmitForm(id)
{
$("#form_" + id).submit();
}
</script>

How to access varibales defined in a controller by a viewer in MVC4

public class TestController : Controller
{
public ActionResult Index()
{
var xmDTO = XFacade.XList();
return View(xmDTO );
}}
My controller is look like that and I want to access the list from my viewer
How to do that ?
I wont come when I use xmDTO in a loop
Why can't you strongly type your view?
public class TestController : Controller
{
public ActionResult Index()
{
var xmDTO = XFacade.XList();
return View(xmDTO );
}
}
in your view
#model XList<type>
#{
ViewBag.Title = "List of string value";
}
#foreach (var item in country in Model)
{
//use properties in item
}
Using ViewBag will be good approach
Controller class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication4.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
ViewBag.country = new List<string>()
{
"USA",
"INDIA",
"UK"
};
return View();
}
}
}
View
#{
ViewBag.Title = "List of string value";
}
<h2>Country List</h2>
<ul>
#foreach (string country in ViewBag .country)
{
<li>#country</li>
}

MVC : System.NullReferenceException model when submit form

I've been trying to pass a model to a partial view with a form. Some of the model fields are already assigned in the GET request. When the form loads I can see the model fields values but after
submiting the form I get this error in this line: #Html.Hidden("From",Model.From):
Object reference not set to an instance of an object
Why these two fields are assigned with null on submit?
My controllers:
[HttpGet]
public ActionResult SendPrivateMessage(string from, List<string> to)
{
// two of the fields are already assigned
return PartialView("SendMessage", new MessageModel(from,to));
}
[HttpPost]
public ActionResult SendPrivateMessage(MessageModel m)
{
string fullname = "";
LoginModel loginData = (LoginModel)(Session["user"]);
if (Session["user"] != null)
{
fullname = loginData.LoginDS.Tables[0].Rows[0][loginData.LoginDS.Tables[0].Columns["fullname"].Ordinal].ToString();
}
m.fullname = fullname;
m.Send();
return PartialView("SendMessage");
}
The partial view:
#model HaifanetMobile.Models.MessageModel
<div id="contact_form">
<a id="back_contact" href="#" style="float:left">
<img style="height:20px; width:30px;" src="~/Images/back_btn.gif" alt="back" />.
</a>
<div id="contactus_title">
<div id="close_contactus" style="float:right"><img style="height:20px; width:20px;" src="~/Images/close_btn.gif" /></div>
</div>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<br />
<fieldset>
#Html.Hidden("From", Model.From) //this is where I get the error
#Html.Hidden("To", Model.To)//this is where I get the error
<div>
#Html.TextBoxFor(m => m.Subject, new { #class = "", placeholder = "subject:", id = "msg_subject", onfocus = "this.placeholder = ''", onblur = "this.placeholder = 'subject:'" })
#Html.ValidationMessageFor(m => m.Subject, "required")
</div>
<div>
#Html.TextAreaFor(m => m.Content, new { #class = "", id = "msg_textarea" })
#Html.ValidationMessageFor(m => m.Content, "required")
</div>
</fieldset>
<p>
<input type="submit" value="send" />
</p>
}
</div>
The Model:
public class MessageModel
{
public string From { get; set; }
public List<string> To { get; set; }
public string Subject {get; set;}
public string Content { get; set; }
public string fullname { get; set; }
public MessageModel(string from, List<string> to)
{
// TODO: Complete member initialization
this.From = from;
this.To = to; ;
}
public MessageModel() {
}
public void Send()
{
ServiceReference2.WebService1Soap ws = new ServiceReference2.WebService1SoapClient();
if (!ws.SendMessage(this.From, this.Content, this.Subject, this.To.ToArray() ,this.fullname))
throw new Exception();
}
}
Thanks in advance
You're forgetting to pass the model to your view.
When you return this view, instead of this:
return PartialView("SendMessage");
you must do this:
return PartialView("SendMessage", m);
Where m is your model. That's why the model is null inside your view.