I have a Model which i want to edit (Location).This model has a field called ActivityId.I am sending an array of ActivityId-s via ViewData to the view and transform them to a SelectList.
I want the ActivityId field (long) of the Location to be set with the selected item from the dropdownlist (string) - i need a conversion done somehow from string to long before entering the Post Action of the controller.(EditConfirmed)
Models:
[Table("location")]
public partial class Location
{
public Location()
{
StoryLocation = new HashSet<StoryLocation>();
UserStoryLocation = new HashSet<UserStoryLocation>();
}
[Column("id", TypeName = "bigint(20)")]
public long Id { get; set; }
[Column("description")]
[StringLength(255)]
public string Description { get; set; }
[Column("name")]
[StringLength(255)]
public string Name { get; set; }
[Column("activity_id", TypeName = "bigint(20)")]
public long? ActivityId { get; set; }
[ForeignKey("ActivityId")]
[InverseProperty("Location")]
public Activity Activity { get; set; }
}
}
[Table("activity")]
public partial class Activity
{
public Activity()
{
Location = new HashSet<Location>();
}
[Column("activity_id", TypeName = "bigint(20)")]
public long ActivityId { get; set; }
[Column("description")]
[StringLength(255)]
public string Description { get; set; }
[Column("name")]
[StringLength(255)]
public string Name { get; set; }
[Column("type")]
[StringLength(255)]
public string Type { get; set; }
[InverseProperty("Activity")]
public ICollection<Location> Location { get; set; }
}
Controller:
[HttpGet]
public IActionResult Edit(long id = 0)
{
Location loc = this.context.Locations.Find(id);
if (loc == null)
{
return NotFound();
}
ViewData[Constants.ViewData.TActivities]=this.context.Activities
.Select(elem=>
new SelectListItem
{
Text=elem.Name,
Value=elem.ActivityId.ToString()
}
).ToList();
return View(loc);
}
View
#using AdminMVC.Models
#using AdminMVC.ConfigConstants
#using Newtonsoft.Json
#model AdminMVC.Models.Location
#{
List<SelectListItem> dropActivities=ViewData[Constants.ViewData.TActivities] as List<SelectListItem>;
}
<html>
<head>
</head>
<body>
<div id="form">
</div>
<div id="page">
#using (Html.BeginForm("Edit","Location",FormMethod.Post))
{
<div id="table">
<label>Set Location:</label>
<table border="">
#Html.DisplayFor(x=>x.Id)
<tr>
<td>#Html.DisplayNameFor(x=>x.Name)</td>
<td>#Html.EditorFor(x=>x.Name)</td>
</tr>
<tr>
<td>#Html.DisplayNameFor(x=>x.Description)</td>
<td>#Html.EditorFor(x=>x.Description)</td>
</tr>
<div>
<label >Select Activity:</label>
#Html.DropDownList("Activity",dropActivities) //i need to somehow convert the selected value from the dropdown to long before the form is sent to the controller
</div>
</table>
</div>
<div id="control-panel">
<input type="submit" value="Edit">
</div>
}
</body>
</div>
</html>
Post to Controller
[HttpPost, ActionName("Edit")]
public IActionResult EditConfirmed(Location editLoc)
{
if (ModelState.IsValid)
{
this.context.Entry(editLoc).State = EntityState.Modified;
this.context.SaveChanges();
return RedirectToAction("Index");
}
return View(editLoc);
}
P.S:So far the ActivityId of the Location sent to the Post Action is null.I need it to be long.
I solved this problem using the ViewData component.I would first serialize the SelectList using NewtonSoft then i would add it to the ViewData dictionary.When rendering the view i would use the DropDownList razor Html Helper method.
Model
public class FixedLocation
{
[Column("id", TypeName = "bigint(20)")]
public long Id { get; set; }
[Column("coords")]
[StringLength(255)]
public string Coords { get; set; }
[Column("name")]
[StringLength(255)]
[Required]
public string Name { get; set; }
[Column("google_id")]
[StringLength(255)]
[Required]
public string GoogleId { get; set; }
}
Extension method for getting a List of SelectListItem
public static IEnumerable<SelectListItem> ToSelectList<T,Tkey,Tvalue>(
this IQueryable<T> myenum,
Func<T,(Tkey,Tvalue)>kvpair)
{
return myenum.Select(elem=>kvpair(elem))
.Select(tuple=>new SelectListItem{
Text=tuple.Item1.ToString(),
Value=tuple.Item2.ToString()
});
}
Controller:
public IActionResult Create()
{
Location targetLocation = new Location();
ViewData[Constants.ViewData.TFixedLocations]=
this.context.FixedLocation
.ToSelectList<FixedLocation,string,long>
(elem=>(elem.Name,elem.Id)).ToList();
return View(targetLocation);
}
View:
#using AdminMVC.Models
#model AdminMVC.Models.Location
#using AdminMVC.ConfigConstants
#{
dropFixedLocations=ViewData[Constants.ViewData.TFixedLocations] as List<SelectListItem>;
}
<div>
<label >Select FixedLocation:</label>
#Html.DropDownListFor(x=>Model.Id,dropFixedLocations)
</div>
Related
I have 2 Separate Tables Products and Product Photo
When I examine any details in the products table, I want the pictures of that product to come. In that case, I pull it into the Detail table in a field called _UrunFotoPartitialView as # html.partitial ("") but always
The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.Urun_C7B3883A1159F8EE0177C29B1CA535182B157B3C5BB798ABCC8C2A72FB5CFED9', but this dictionary requires a model item of type 'Tututuncu.Models.UrunFotoViewModel'.
gives an error. How many days I have been dealing but I couldn't do it.
Ürün Class
public partial class Urun
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Urun()
{
this.Firma = new HashSet<Firma>();
this.Musteri = new HashSet<Musteri>();
this.Satis = new HashSet<Satis>();
}
public int UrunID { get; set; }
public Nullable<int> UrunFotoID { get; set; }
public Nullable<int> MarkaID { get; set; }
public string UrunAdi { get; set; }
public Nullable<decimal> UrunFiyat { get; set; }
public Nullable<decimal> UrunAlisFiyat { get; set; }
public Nullable<int> UrunStok { get; set; }
public string UrunAciklama { get; set; }
public Nullable<System.DateTime> UretimYili { get; set; }
public Nullable<System.DateTime> EklenmeTarihi { get; set; }
public Nullable<System.DateTime> GuncellenmeTarihi { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Firma> Firma { get; set; }
public virtual Markalar Markalar { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Musteri> Musteri { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Satis> Satis { get; set; }
public virtual UrunFoto UrunFoto { get; set; }
}
Ürün Foto Class
public partial class UrunFoto
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public UrunFoto()
{
this.Urun = new HashSet<Urun>();
}
public int FotoID { get; set; }
public Nullable<int> UrunFotoID { get; set; }
public string BuyukYol { get; set; }
public string OrtaYol { get; set; }
public string KucukYol { get; set; }
public Nullable<bool> Varsayilan { get; set; }
public string SiraNo { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Urun> Urun { get; set; }
}
My UrunController
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Tututuncu.Models;
namespace Tututuncu.Areas.Yonetim.Controllers
{
[Authorize]
public class UrunController : Controller
{
private StokDBEntities db = new StokDBEntities();
// GET: Yonetim/Urun
public ActionResult Index()
{
return RedirectToAction("Listele");
}
public ActionResult Listele()
{
var urun = db.Urun.Include(u => u.Markalar).Include(u => u.UrunFoto);
return View(urun.ToList());
}
public ActionResult Yeni()
{
ViewBag.MarkaID = new SelectList(db.Markalar, "MarkaID", "MarkaAd");
ViewBag.UrunFotoID = new SelectList(db.UrunFoto, "FotoID", "BuyukYol");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Yeni([Bind(Include = "UrunID,UrunFotoID,MarkaID,UrunAdi,UrunFiyat,UrunAlisFiyat,UrunStok,UrunAciklama,UretimYili,EklenmeTarihi,GuncellenmeTarihi")] Urun urun)
{
if (ModelState.IsValid)
{
db.Urun.Add(urun);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.MarkaID = new SelectList(db.Markalar, "MarkaID", "MarkaAd", urun.MarkaID);
ViewBag.UrunFotoID = new SelectList(db.UrunFoto, "FotoID", "BuyukYol", urun.UrunFotoID);
return View(urun);
}
public ActionResult Guncelle(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Urun urun = db.Urun.Find(id);
if (urun == null)
{
return HttpNotFound();
}
ViewBag.MarkaID = new SelectList(db.Markalar, "MarkaID", "MarkaAd", urun.MarkaID);
ViewBag.UrunFotoID = new SelectList(db.UrunFoto, "FotoID", "BuyukYol", urun.UrunFotoID);
return View(urun);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Guncelle([Bind(Include = "UrunID,UrunFotoID,MarkaID,UrunAdi,UrunFiyat,UrunAlisFiyat,UrunStok,UrunAciklama,UretimYili,EklenmeTarihi,GuncellenmeTarihi")] Urun urun)
{
if (ModelState.IsValid)
{
db.Entry(urun).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.MarkaID = new SelectList(db.Markalar, "MarkaID", "MarkaAd", urun.MarkaID);
ViewBag.UrunFotoID = new SelectList(db.UrunFoto, "FotoID", "BuyukYol", urun.UrunFotoID);
return View(urun);
}
public ActionResult Sil(int id)
{
var silinecekUrun = db.Urun.Find(id);
if (silinecekUrun == null)
return HttpNotFound();
db.Urun.Remove(silinecekUrun);
db.SaveChanges();
return RedirectToAction("Index", "Urun");
}
public ActionResult UrunResimEkle(int id)
{
Urun urun = db.Urun.Find(id);
ViewBag.Foto = urun;
return View(urun);
}
public ActionResult FotoListele(int id)
{
Urun urun = db.Urun.Find(id);
ViewBag.Foto = urun;
return View(urun);
}
[HttpPost]
public ActionResult UrunResimEkle(int uId, HttpPostedFileBase fileUpload)
{
if (fileUpload != null)
{
Image img = Image.FromStream(fileUpload.InputStream);
Bitmap kucukResim = new Bitmap(img, ResimAyar.UrunKucukBoyut);
Bitmap ortaResim = new Bitmap(img, ResimAyar.UrunOrtaBoyut);
Bitmap buyukResim = new Bitmap(img, ResimAyar.UrunBuyukBoyut);
string buyukYol = "/images/UrunFoto/Buyuk/" + Guid.NewGuid() + VirtualPathUtility.GetExtension(fileUpload.FileName);
string ortaYol = "/images/UrunFoto/Orta/" + Guid.NewGuid() + VirtualPathUtility.GetExtension(fileUpload.FileName);
string kucukYol = "/images/UrunFoto/Kucuk/" + Guid.NewGuid() + VirtualPathUtility.GetExtension(fileUpload.FileName);
kucukResim.Save(Server.MapPath(kucukYol));
ortaResim.Save(Server.MapPath(ortaYol));
buyukResim.Save(Server.MapPath(buyukYol));
UrunFoto rsm = new UrunFoto();
rsm.BuyukYol = buyukYol;
rsm.OrtaYol = ortaYol;
rsm.KucukYol = kucukYol;
rsm.UrunFotoID = uId;
if (db.UrunFoto.FirstOrDefault(x => x.UrunFotoID == uId && x.Varsayilan == false) != null)
rsm.Varsayilan = true;
else
rsm.Varsayilan = false;
db.UrunFoto.Add(rsm);
db.SaveChanges();
return Redirect(ControllerContext.HttpContext.Request.UrlReferrer.ToString());
}
return View(uId);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Urun View Page
#model IEnumerable<Tututuncu.Models.Urun>
#{
ViewBag.Title = "Ürüne Resim Ekle";
Layout = "~/Areas/Yonetim/Views/Shared/_Layout.cshtml";
}
<!-- Page Content -->
<div id="page-wrapper">
<div class="container-fluid">
<div class="row bg-title">
<div class="col-lg-3 col-md-4 col-sm-4 col-xs-12">
<h4 class="page-title">File Upload</h4>
</div>
<div class="col-lg-9 col-sm-8 col-md-8 col-xs-12">
<ol class="breadcrumb">
<li>Yönetim Paneli</li>
<li class="active">File Upload</li>
</ol>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- .row -->
<div class="row">
<div class="col-sm-12 ol-md-6 col-xs-12">
<div class="white-box">
<h3 class="box-title">File Upload1</h3>
<label for="input-file-now">Your so fresh input file — Default version</label>
<form action="/Yonetim/Urun/UrunResimEkle" method="post" enctype="multipart/form-data">
<input type="hidden" name="uId" value="#Model" />
<input type="file" name="fileUpload" />
<input type="submit" name="name" value="Kaydet" class="btn btn-primary" />
</form>
</div>
</div>
</div>
#Html.Partial("FotoListele")
</div>
</div>
My Partitial View Page
#model IEnumerable<Tututuncu.Models.UrunFoto>
#{
ViewBag.Title = "FotoListele";
Layout = "~/Areas/Yonetim/Views/Shared/_Layout.cshtml";
}
<h2>FotoListele</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.BuyukYol)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.BuyukYol)
</td>
</tr>
}
</table>
You have two model types.
Parent: #model IEnumerable<Tututuncu.Models.Urun>
Partial: #model IEnumerable<Tututuncu.Models.UrunFoto>
You're calling Partial using #Html.Partial("FotoListele")
You can use #Html.Partial("FotoListele", THE-NEW-MODEL-OF-LIST-UrunFoto)
When using Partial without passing the new model, it uses the parent model. Thus, it gets exception when trying to perform the casting.
You can either create a new Model that fits the Partial needs, or accept the parent model.
Note: partial class doesn't relate at all to razor engine Html.Partial. more on that Here
I am using autogenerated entity model classes and than i used partial class with metadata to put validations on auto genetrated classes like below.
public class tblDepartmentCustom
{
[Key]
public int DepartmentId { get; set; }
[Required(ErrorMessage = "Department name is required")]
public string DepartmentName { get; set; }
}
[MetadataType(typeof(tblDepartmentCustom))]
public partial class tblDepartmentMaster
{
}
The original class that was generated by entity framework is given below.
public partial class tblDepartmentMaster
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public tblDepartmentMaster()
{
this.tblDesignationMasters = new HashSet<tblDesignationMaster>();
}
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<tblDesignationMaster> tblDesignationMasters { get; set; }
}
So the problem here is that whenever i try to validated model state it comes out to be true.below is the code.
#model EmployeeManager.Models.tblDepartmentCustom
#{
ViewBag.Title = "InsertDepartment";
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}<div class="col-md-4">
#using (Html.BeginForm("InsertDepartment", "Departments", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<span class="error-class">#ViewBag.FoundError</span>
<br />
<label>Department Name</label>
#Html.TextBoxFor(m => m.DepartmentName, new { #class = "form-control" })
<br />
<input type="submit" class="btn btn-info" value="Add Department" />
}
</div>
And the action below.
[HttpGet]
public ActionResult InsertDepartment()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
[ActionName("InsertDepartment")]
public ActionResult InsertDepartmentPost()
{
using (PMSEntities dc = new PMSEntities())
{
tblDepartmentMaster dm = new tblDepartmentMaster();
TryUpdateModel(dm);
if(ModelState.IsValid)
{
dc.tblDepartmentMasters.Add(dm);
dc.SaveChanges();
return View("_Success");
}
else
{
ViewBag.FoundError = "Department name is required.";
return View();
}
}
}
In order for partial classes to work, both partials must have the same namespace. You don't have to move the actual files around your file structure, just edit the namespace of tblDepartmentCustom to match that of tblDepartmentMaster.
I am not able to save the record after implementing the drop down field. Can someone please correct my code.
Create.cshtml
#model SomeIndianShit.Models.Accommodation
#{
ViewBag.Title = "Advertise Accommodation";
}
<form name="datapluspics" method="post" enctype="multipart/form-data">
#Html.ValidationSummary(true)
<fieldset>
<legend>Accommodation</legend>
<div class="editor-label">
#Html.LabelFor(model => model.State)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.SelectedAustraliaStateId, Model.AustraliaStates)
</div>
<p>
<input type="submit" value=" Save " />
</p>
</fieldset>
</form>
My Model:
public class AustraliaStates
{
[Key]
public string AustraliaStateId { get; set; }
public string AustraliaStateName { get; set; }
}
public class Accommodation
{
[Key]
public string A_Unique_Id { get; set; }
[Display(Name = "Ad Id")]
public string Ad_Id { get; set; }
[Display(Name = "Posted By")]
public string User { get; set; }
[Display(Name = "Street")]
public string Street { get; set; }
[Required]
[Display(Name = "Suburb")]
public string Suburb { get; set; }
[Required]
[Display(Name = "State")]
public string State { get; set; }
public byte[] Picture1 { get; set; }
public string SelectedAustraliaStateId { get; set; }
public IEnumerable<SelectListItem> AustraliaStates { get; set; }
}
AccommodationController.cs
// GET: /Accommodation/Create
[Authorize]
public ActionResult Create()
{
var model = new Accommodation
{
AustraliaStates = db.AustraliaStates
.ToList()
.Select(x => new SelectListItem
{
Text = x.AustraliaStateName,
Value = x.AustraliaStateId
})
};
return View(model);
}
/ POST: /Accommodation/Create
[Authorize]
[HttpPost]
public ActionResult Create(Accommodation accommodation, HttpPostedFileBase file1, HttpPostedFileBase file2, HttpPostedFileBase file3)
{
if (ModelState.IsValid)
{
// save and redirect
// ...blah blah...
//blah blah...
db.Accommodation.Add(accommodation);
//Save in Database
db.SaveChanges();
return RedirectToAction("Index");
}
// repopulate SelectList properties [I THINK THIS IS WRONG]
var model = new Accommodation
{
AustraliaStates = db.AustraliaStates
.ToList()
.Select(x => new SelectListItem
{
Text = x.AustraliaStateName,
Value = x.AustraliaStateId
})
};
return View(accommodation);
}
After filling the form, when save button is clicked, the following error message is displayed
The ViewData item that has the key 'SelectedAustraliaStateId' is of type 'System.String' but must be of type 'IEnumerable'.
In your HttpPost controller action you need to repopulate the correct property on the model that you are passing to the view, i.e. set the AustraliaStates on your model the same way you are doing in your GET action:
accommodation.AustraliaStates = db.AustraliaStates
.ToList()
.Select(x => new SelectListItem
{
Text = x.AustraliaStateName,
Value = x.AustraliaStateId
});
return View(accommodation);
I have a view that is created dynamically with objects from my database. How can I take the values from my View and pass them to my view model if it is created dynamically? I know this question is vague but hopefully looking through my code will help you help me.
View
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm()) {%>
<h1>Survey Says...</h1>
<ol>
<li>
Name: <input type="text" disabled="true" name="name" value="<%= Model.Name %>"/>
</li>
<li>
Email: <input type="text" disabled="true" name="email" value="<%= Model.Email %>"/>
</li>
<%foreach(SurveyQuestions s in Model.myQuestions)
{ %>
<li> <%= s.QuestionText %> <br />
<%
foreach(SurveyQuestionAnswers q in s.QuestionAnswers)
{
%>
<input type="radio" name="rbGroup<%= q.Id%>"/> <%= q.DisplayText %><br/>
<%
if(q.IsEditable)
{
%>
<input type="text" id="txtOther<%= q.Id %>"/>
<%
}
}
%>
</li>
<% }
%>
<li>
<input type="submit" value="Save" id="save-button" />
</li>
</ol>
<% } %>
SurveyQuestion class
public class SurveyQuestions
{
public string QuestionText { get; set; }
public List<SurveyQuestionAnswers> QuestionAnswers { get; set; }
public int Id { get; set; }
}
SurveyQuestionAnswers class
public class SurveyQuestionAnswers
{
public int Id { get; set; }
public string DisplayText { get; set; }
public bool IsEditable { get; set; }
}
My sloppy ViewModel
public class GfcPreInterventionSurveyViewModel
{
static SurveyService myService = new SurveyService(new SurveyRepository());
[DisplayName("Name")]
[Required(ErrorMessage = "Name is required.")]
public string Name { get; set; }
[DisplayName("Work Email")]
[Email(ErrorMessage = "The email you entered is not valid.")]
public string Email { get; set; }
[DisplayName("Gender")]
[Required(ErrorMessage = "Gender is required.")]
public string Gender { get; set; }
[DisplayName("Country")]
[Required(ErrorMessage = "Country is required.")]
public string Country { get; set; }
[DisplayName("Business")]
[Required(ErrorMessage = "Please select a business unit.")]
public string BusinessUnit { get; set; }
public SelectList GenderList;
public SelectList BusinessList;
public SelectList CountryList;
public SelectList RoutineList;
public SelectList ReasonList;
public SelectList ActivityList;
public SelectList HealthList;
public SelectList EnergyList;
public SelectListItem GenderItem;
public SelectListItem BusinessItem;
public SelectListItem CountryItem;
public SelectListItem RoutineItem;
public SelectListItem ReasonItem;
public SelectListItem ActivityItem;
public SelectListItem HealthItem;
public SelectListItem EnergyItem;
public Boolean ToGetFit { get; set; }
public Boolean ToChallengeMyself { get; set; }
public Boolean ToIncrEnergy { get; set; }
public Boolean ToBuildMorale { get; set; }
public Boolean ToBeHealthier { get; set; }
public Boolean ChallengeOther { get; set; }
public string OtherString { get; set; }
[DisplayName("Exercise Routine")]
[Required(ErrorMessage = "Which option describes your exercise routine.")]
public string Routine { get; set; }
[DisplayName("Physical Activity")]
[Required(ErrorMessage = "Which option describes your physical activity.")]
public string Activity { get; set; }
[DisplayName("Overall Health")]
[Required(ErrorMessage = "Which option describes your overall health.")]
public string Health { get; set; }
[DisplayName("Energy")]
[Required(ErrorMessage = "Which option best describes your energy.")]
public string Energy{ get; set; }
public int ReasonsForChallenge { get; set; }
public List<SurveyQuestions> myQuestions = new List<SurveyQuestions>();
//public List<SurveyQuestionAnswers> myAnswers;
public void build(int id)
{
var myService = new SurveyService(new SurveyRepository());
myQuestions = myService.GetSurveyQuestions(id);
}
my getSurveyQuestions method returns a List of SurveyQuestions objects.
currently, in my controller, when save is hit, the post method is called. this is where i want to update my database with the values in the viewmodel, but because my page is so dynamic, i am having trouble accessing the user's input.
My Controller:
public class SurveyController : WidgetControllerBase
{
#region Private Members
private readonly ISurveyRepository _surveyRepository;
#endregion
#region Constructors
public SurveyController(ISurveyRepository surveyRepository)
{
if (surveyRepository == null)
{
throw new ArgumentNullException("surveyRepository");
}
_surveyRepository = surveyRepository;
}
#endregion
// GET: /Survey/GfcPreIntervention
public ActionResult GfcPreInterventionSurvey()
{
var surveyService = new SurveyService();
var vm = new GfcPreInterventionSurveyViewModel();
vm.build(AppUserInstance.Id);
//paymentService.SetDVDShipped(payment.PaymentId);
return View(vm);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GfcPreInterventionSurvey(GfcPreInterventionSurveyViewModel viewModel)
{
return View(viewModel);
}
}
Since your page is highly dynamic, maybe you would be better off writing a custom model binder. Though the term sounds intimidating it’s not actually that complicated.
You would simply create a class which would implement IModelBinder. Within this class, you would have access to the form collection and can populate any complex object(s) with it
Following are some examples worth looking at
http://dotnetslackers.com/articles/aspnet/Understanding-ASP-NET-MVC-Model-Binding.aspx
http://ivanz.com/2010/11/03/custom-model-binding-using-imodelbinder-in-asp-net-mvc-two-gotchas/
And as you have figured out, using helper methods (preferably with Razor) will clean up the UI code
I have a list of comments under my detail page in MVC. I want the user to be able to add comments in the same page and save to the database. How do I pass data to the controller action and save this using dbcontext that holds my comment class.
I have this follow code in my CommentController:
public ActionResult Create(int MovieId)
{
var moviecomment = _db.Moviecomment.Where(r => r.MovieID == MovieId);
return View(moviecomment);
}
[HttpPost]
public ActionResult Create(MovieComment Moviecomment)
{
var MovieComment = _db.Moviecomment.Add(Moviecomment);
_db.SaveChanges();
return RedirectToAction("Details");
}
And has a partial View:
#model MvcMovie.Models.MovieComment
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<div class="addcommentbox">
<h2> Add Comment </h2>
#Html.TextAreaFor(model => model.comment)
<div class="ErrorMessage">
#Html.ValidationMessageFor(model => model.comment)
</div>
<input id="addComment" type="button" onclick="" value="Add" />
</div>
}
and in my Detail page i have this:
#model MvcMovie.Models.Movie
#{
ViewBag.Title = "Details";
}
<h2>Details</h2>
Movie
Title
#Html.DisplayFor(model => model.Title)
Genre
#Html.DisplayFor(model => model.Genre)
PostDate
#Html.DisplayFor(model => model.PostDate)
Staring
#Html.DisplayFor(model => model.Staring)
Description
#Html.DisplayFor(model => model.Description)
Trailer
#Html.DisplayFor(model => model.Trailer)
<fieldset>
#Html.Partial("Comments",Model.MovieComment)
</fieldset>
<p>
</p>
<p>
#Html.ActionLink("Edit", "Edit", new { id=Model.MovieID }) |
#Html.ActionLink("Back to List", "Index")
</p>
#Html.RenderAction("Create","Comment" new { id = Model.MovieID })
i want user to able to add comment when they are in detail page: other thing seem to been fine but this line
#Html.RenderAction("Create","Comment" new { id = Model.MovieID })
give me the following error. cannot implicitly convert type void to object. Please any help will be appreciated.
The model code:
public class Movie
{
public int MovieID { get; set; }
public string Title { get; set; }
public String Genre { get; set; }
public DateTime PostDate { get; set; }
public string Staring { get; set; }
public string Description { get; set; }
public string Picture { get; set; }
public string Trailer { get; set; }
public virtual ICollection< MovieComment> MovieComment { get; set; }
}
For comment
public class MovieComment
{
// public MovieComment()
//{
// Movie = new HashSet<Movie>();
//}
public int MovieCommentID { get; set; }
public string comment_title { get; set; }
public String comment { get; set; }
public int MovieID { get; set; }
// [ForeignKey("ID")]
public virtual Movie Movie { get; set; }
//[ForeignKey("ProfileID")]
public virtual Profile Profile { get; set; }
public String ProfileID { get; set; }
//public string MovieUserID { get; set; }
}
Not sure if this is your only error, but the syntax is wrong for the line that's giving you an error. You are missing a comma. Try:
#Html.RenderAction("Create","Comment", new { id = Model.MovieID })
If this doesn't fix your problem, can you also post the code for your model?