How to pass an array from mvc controller to java script in HTML.CS page
This is My Model
public class Event
{
public int ID { get; set; }
public string StartDate { get; set; }
public string EndDate { get; set; }
public string Description { get; set; }
}
And My Controller
public IActionResult Calendar()
{
ViewData["User"] = user;
ViewData["Events"] = events;
return View();
}
Hope it helps
In controller:
public IActionResult Calendar()
{
var users = db.Users;
var events = db.Events.ToList();
ViewData["events"] = events; // Send this list to the view
return View(users .ToList());
}
In view:
#model IEnumerable<Models.User>
#{
var events= (List<Event>) ViewData["events"]; // Cast events to list
}
#foreach (var e in #events) // Print the list
{
#Html.Label(e.Description);
}
<table>
...
#foreach (var item in Model)
{
... // each user in here in item
}
</table>
Related
I want to pass to RedirectToAction model with List type property
For example, I have this simple model:
public class OrgToChooseFrom
{
public string OrgId { get; set; }
public string FullName { get; set; }
}
And complex model as this:
public class SelectCounteragentViewModel
{
public List<OrgToChooseFrom> Counteragents { get; set; }
public OrgToChooseFrom SelectedOrg { get; set; }
}
When I pass simple model with RedirectToAction every value is in place
[HttpGet]
public IActionResult ConfirmChoice(OrgToChooseFrom vm)
{
return View(vm);
}
But when I try to pass complex model SelectCounteragentViewModel, there are empty list and null for the "SelectedOrg" field
[HttpGet]
public IActionResult SelectFromCAOrganizations(SelectCounteragentViewModel vm)
{
return View(vm);
}
How can I do it?
RedirectToAction cannot pass complex model.You can try to use TempData as
Kiran Joshi said.Here is a demo:
public IActionResult Test()
{
SelectCounteragentViewModel vm = new SelectCounteragentViewModel { Counteragents = new List<OrgToChooseFrom> { new OrgToChooseFrom { OrgId ="1", FullName = "d" } }, SelectedOrg = new OrgToChooseFrom { OrgId = "1", FullName = "d" } };
TempData["vm"] = JsonConvert.SerializeObject(vm);
return RedirectToAction("SelectFromCAOrganizations", "ControllerName");
}
[HttpGet]
public IActionResult SelectFromCAOrganizations()
{
SelectCounteragentViewModel vm = JsonConvert.DeserializeObject<SelectCounteragentViewModel>(TempData["vm"].ToString());
return View(vm);
}
I'm having a trouble with my project (ASP.NET MVC 5/AJAX/BOOTSTRAP).
When click on Save button on Page, .Net calls in POST the proper action, but the Hidden Fields for PSATOKEN does not contain value (see #Html.HiddenFor(m => m.PSAToken) in the View), despite PSAToken contains a GUID value (saw in Debug Mode) in the Controller method.
Let's see some code below.
Many thanks to answerers!
Model
public interface IPSAPageViewModel
{
String PSAToken { get; set; }
int IdPSAAzienda { get; set; }
}
public abstract class BasePSAPageViewModel : IPSAPageViewModel
{
public String PSAToken { get; set; }
public int IdPSAAzienda { get; set; }
}
public class DatiGeneraliViewModel : BasePSAPageViewModel
{
public DatiGeneraliViewModel()
{
this.Item = new InformazioniGenerali();
}
public Crea.PSA.ServiceLayer.BO.InformazioniGenerali Item { get; set; }
public List<SelectListItem> FormeGiuridicheList { set; get; }
public List<SelectListItem> FormeConduzioneList { set; get; }
}
Controller
private ViewResult ViewPSAPage(IPSAPageViewModel vm)
{
base.createViewBagPaginePrecSucc();
return View(vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
[HttpParamAction]
public ActionResult SalvaDatiGeneraliProsegui(DatiGeneraliViewModel vm)
{
return salvataggioDatiGenerali(vm, true);
}
[HttpPost]
[ValidateAntiForgeryToken]
[HttpParamAction]
public ActionResult SalvaDatiGenerali(DatiGeneraliViewModel vm)
{
//Here vm.PSAToken doesn't contain the value setted
return salvataggioDatiGenerali(vm);
}
private ActionResult salvataggioDatiGenerali(DatiGeneraliViewModel vm, bool proseguiCompilazione = false)
{
if (ModelState.IsValid)
{
var resp = aziendeManager.Save(vm.PSAToken, vm.Item, SessionManager.UserIdConnected, CONTROLLERNAME);
if (resp.Success)
{
var psaAzienda = resp.DataObject;
setVarsInSession(psaAzienda.idToken.ToString(), psaAzienda.idPsaAzienda.ToString(), psaAzienda.Aziende.ragioneSociale);
//Here there is some Value (POST)
vm.PSAToken = psaAzienda.idToken.ToString();
//vm.IdPSAAzienda = psaAzienda.idPsaAzienda.ToString();
if (proseguiCompilazione)
return RedirectToAction("DatiAziendaliRiepilogativi", new { id = psaAzienda.idToken });
}
else
ModelState.AddModelError("", resp.Message);
}
setSuccessMessage();
vm.FormeGiuridicheList = aziendeManager.GetAllFormeGiuridiche().ToSelectItems();
vm.FormeConduzioneList = aziendeManager.GetAllFormeConduzione().ToSelectItems();
return ViewPSAPage(vm);
}
View
to see the view click here
Here you can see the value at debug in VS
But in the generated HTML the Hidden Field of PSATOKEN is empty
I found the solution here:
patrickdesjardins.com/blog/… .
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I got null reference exception when i trying to view data from table for actually logged user - Klient_has_sklep and if that user isnt signed with Sklep table.
When i viewing data for user who is signed with Sklep table everything is ok.
I think problem is in Controller with viewModel
This is my controller
public ActionResult Index(int? id)
{
var viewModel = new Klient_has_SklepIndexData();
viewModel.Klients = db.Klients
.OrderBy(i => i.Nazwisko);
UserManager UM = new UserManager();
int idZalogowanego = UM.GetUserID(User.Identity.Name);
ViewBag.idzal = idZalogowanego;
viewModel.Klient_has_Skleps = viewModel.Klients.Where(i => i.SYSUserID == idZalogowanego).Single().Klient_has_Sklep;
return View(viewModel);
}
This is my view
#model Sklepy.Models.ViewModel.Klient_has_SklepIndexData
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>#ViewBag.idzal.</h2>
<h2>Twoje zniżki w sklepach</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>asd</th>
</tr>
#if (Model != null)
{
#foreach (var item in Model.Klient_has_Skleps)
{
<tr>
<td>#item.Znizka1</td>
</tr>
}
}
</table>
This is my Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sklepy.Models.DB;
namespace Sklepy.Models.ViewModel
{
public class Klient_has_SklepIndexData
{
public IEnumerable<Klient> Klients { get; set; }
public IEnumerable<Klient_has_Sklep> Klient_has_Skleps {get; set;}
}
}
Klient class code
public partial class Klient
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Klient()
{
this.Klient_has_Sklep = new HashSet<Klient_has_Sklep>();
}
public int KlientID { get; set; }
public int SYSUserID { get; set; }
public string Imię { get; set; }
public string Nazwisko { get; set; }
public string Adres { get; set; }
public string Telefon { get; set; }
public string Email { get; set; }
public virtual SYSUser SYSUser { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Klient_has_Sklep> Klient_has_Sklep { get; set; }
}
Create your ViewModel as shown below. I made modification to make default initialization with List.
public class Klient_has_SklepIndexData
{
public IList<Klient> Klients { get; set; }
public IList<Klient_has_Sklep> Klient_has_Skleps { get; set; }
public Klient_has_SklepIndexData()
{
Klients = new List<Klient>();
Klient_has_Skleps = new List<Klient_has_Sklep>();
}
}
And your Action Code.
public ActionResult Index(int? id)
{
var viewModel = new Klient_has_SklepIndexData();
viewModel.Klients = db.Klients
.OrderBy(i => i.Nazwisko).ToList();
UserManager UM = new UserManager();
int idZalogowanego = UM.GetUserID(User.Identity.Name);
ViewBag.idzal = idZalogowanego;
var skelp = viewModel.Klients.FirstOrDefault(i => i.SYSUserID == idZalogowanego);
if(skelp != null){
if(skelp.Klient_has_Sklep != null){
viewModel.Klient_has_Skleps = skelp.Klient_has_Sklep.ToList();
}
}
return View(viewModel);
}
I have no idea what's the reason, it's so straight and simple, but, curiously, doesn't work. I always recieve NULL as model in controller.
Here is the code:
Model
public class EnrolleePlaces
{
[HiddenInput(DisplayValue=false)]
public int id { get; set; }
public string SpecialtyCode { get; set; }
public string Specialty { get; set; }
public int Places { get; set; }
}
Controller
public ViewResult EditPlaces(int id)
{
return View(repo.EnrolleePlaces.FirstOrDefault(p => p.id == id));
}
[HttpPost]
public ActionResult NewPlaces(EnrolleePlaces places) // 'places' is ALWAYS null
{
if (ModelState.IsValid)
{
repo.SaveEnrolleePlaces(places);
return RedirectToAction("Settings");
}
return View("EditPlaces", places);
}
public ViewResult CreatePlaces()
{
return View("EditPlaces", new EnrolleePlaces());
}
And a view
#model Domain.Entities.EnrolleePlaces
#{
Layout = null;
}
Edit: #Model.Specialty
#using (Ajax.BeginForm("NewPlaces", "Enrollee", new { area = "Admin" },
new AjaxOptions() { UpdateTargetId = "AdminContent" } ,
new { enctype = "multipart/form-data" }))
{
#Html.EditorForModel()
// here is input type="submit"
}
I have over 15 controllers in my project, made by the same pattern, but only this one is strange
have you tried changing the name of the parameter that your action method receives ?
for example:
[HttpPost]
public ActionResult NewPlaces(EnrolleePlaces dd) // any name other than "places"
{
if (ModelState.IsValid)
{
repo.SaveEnrolleePlaces(places);
return RedirectToAction("Settings");
}
return View("EditPlaces", places);
}
I am building a web application in ASP.NET MVC. I have a comment page where comments are displayed in a list with the latest to oldest and also have a form at the bottom where a user can post new comments.
Form entries should also be highlighted in addition to having the page displaying the latest comments.
Whats the best way to do this, where displayed data and a post form are on the same page?
Is it possible to do this without ajax as well ?
--Code extract--
class CommentsViewModel
{
public IList<Comment> comments { get; set; }
public Comment comment { get; set; }
public SelectList commentCategories { get; set; }
}
class Comment
{
[Required]
public string commentData { get; set; }
[Required]
public int? commentCategory { get; set; }
}
class Comments : Controller
{
public ActionResult Index()
{
Site db = new Site();
CommentsViewModel commenstVm = new
{
comments = db.GetComments(),
comment = new Comment(),
commentCategories = db.GetCommentCategories()
};
return View(commentsVm);
}
[HttpPost]
public ActionResult AddNewComment(CommentsViewModel commentVm)
{
Site db = new Site();
if (!ModelState.IsValid)
{
return View("Index", commentVm);
}
db.AddComment(commentVm.comment);
return RedirectToAction("Index");
}
}
Here's a basic View and the Controller that you can use as a starting point.
Model and ViewModel:
public class CommentsViewModel
{
public IList<Comment> comments { get; set; }
public CommentsViewModel()
{
comments = new List<Comment>();
}
}
public class Comment
{
[Required]
public string commentData { get; set; }
/** Omitted other properties for simplicity */
}
View:
#using (#Html.BeginForm("Index", "Comments"))
{
#Html.TextBoxFor(t => t.comment.commentData)
#Html.ValidationMessageFor(t=> t.comment.commentData, "", new {#class = "red"})
<button name="button" value="addcomment">Add Comment</button>
}
#foreach (var t in Model.comments)
{
<div>#t.commentData</div>
}
Controller:
public class CommentsController : Controller
{
/** I'm using static to persist data for testing only. */
private static CommentsViewModel _viewModel;
public ActionResult Index()
{
_viewModel = new CommentsViewModel();
return View(_viewModel);
}
[HttpPost]
public ActionResult Index(Comment comment)
{
if (ModelState.IsValid)
{
_viewModel.comments.Add(
new Comment() {commentData = comment.commentData});
return View("Index", _viewModel);
}
return RedirectToAction("Index");
}
}