Using partial view updates asp.net ajax - c#

Trying to display only one comment from the text box in the partial view.
To get some data you need the Session Controller:
private ConferenceContext context = new ConferenceContext();
//
// GET: /Session/
public ActionResult Index()
{
ConferenceContext context = new ConferenceContext();
List<Session> sessions = context.Sessions.ToList();
return View(sessions);
}
//
// GET: /Session/Details/5
public ActionResult Details(int id = 0)
{
Session session = context.Sessions.Find(id);
if (session == null)
{
return HttpNotFound();
}
return View(session);
}
Details View in the Session Folder:
#model Conference.Models.Session
<h3>
#Model.Title
</h3>
<div>
#Model.Abstract
</div>
#Html.Action("_GetForSession", "Comment", new { SessionID = Model.SessionID })
Then the CommentController, which is using the partial view _GetForSession to display the text from the Text Box:
ConferenceContext context = new ConferenceContext();
public PartialViewResult _GetForSession(Int32 sessionID)
{
ViewBag.SessionID = sessionID;
List<Comment> comments = context.Comments.Where(c => c.SessionID == sessionID).ToList();
return PartialView("_GetForSession", comments);
}
[ChildActionOnly()]
public PartialViewResult _CommentForm(Int32 sessionID)
{
Comment comment = new Comment() { SessionID = sessionID };
return PartialView("_CommentForm", comment);
}
[ValidateAntiForgeryToken()]
public PartialViewResult _Submit(Comment comment)
{
context.Comments.Add(comment);
context.SaveChanges();
List<Comment> comments = context.Comments.Where(c => c.SessionID == comment.SessionID).ToList();
ViewBag.SessionID = comment.SessionID;
return PartialView("_GetForSession", comments);
}
Here is the _GetForSession View from the Comment folder:
#model IEnumerable<Conference.Models.Comment>
<div id="comments">
<ul>
#foreach (var comment in Model)
{
<li>#comment.Content</li>
}
</ul>
#using(Ajax.BeginForm("_Submit", "Comment", new AjaxOptions() { UpdateTargetId = "comments" }))
{
#Html.AntiForgeryToken();
#Html.Action("_CommentForm", new { SessionID = ViewBag.SessionID })
}
</div>
The _GetForSession gets its data from the _CommentForm in the Comment folder:
#model Conference.Models.Comment
#Html.HiddenFor(m => m.SessionID)
<div>
#Html.LabelFor(m => m.Content)
#Html.EditorFor(m => m.Content)
</div>
<button type="submit">Submit Comment</button>
Now the main Context would be coming from ConferenceContext in the Models:
public class ConferenceContext : DbContext
{
public DbSet<Session> Sessions { get; set; }
public DbSet<Speaker> Speakers { get; set; }
public DbSet<Comment> Comments { get; set; }
}
And the Context itself from the ConferenceContextInitializer:
public class ConferenceContextInitializer : DropCreateDatabaseAlways<ConferenceContext>
{
protected override void Seed(ConferenceContext context)
{
context.Sessions.Add(
new Session()
{
Title = "Partial View",
Abstract = "View Within the Main",
Speaker = context.Speakers.Add(new Speaker()
{
Name = "John Smith",
EmailAddress = "johnsmith#nowhere.com"
})
});
context.SaveChanges();
}
}
So, my question is can it be possible to display only one comment in the partial view not two?

Related

Call HttpPost with Ajax.BeginForm not work

I tried to call method from controller with Ajax, but it never enters the method, i'm import unobtrusive and validate in Bundle, and always refresh all the page. I'm first time in C# i use vb.net, maybe it's a basical error, but i search a lot and try diferent ways and nothing. thanks for ur time and i hope someone can help me
Update: i have a form inside Master page and that generate the problem D:
View
#model PlanificacionOperacional.Models.FiltroView
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section Styles
{
#Styles.Render("https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css")
#Styles.Render("https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/css/bootstrap-select.min.css")
}
<div class="card-header header-elements-inline" style="padding-top:0;"><h4 class="card-title">Muestreos</h4></div>
<fieldset>
#using (Ajax.BeginForm("Filtrar", "Muestreo",
new AjaxOptions
{
UpdateTargetId = "tabless",
HttpMethod = "POST"
}))
{
<div class="form-group">
#Html.DropDownListFor(model => model.predio, new SelectList(ViewBag.formularios, "id", "nombre"), new { #class = "selectpicker", data_live_search = "true", title = "Predio" })
#Html.DropDownListFor(model => model.zona, new SelectList(ViewBag.zonas, "id", "nombre"), new { #class = "selectpicker", data_live_search = "true", title = "Zona" })
#Html.DropDownListFor(model => model.area, new SelectList(ViewBag.areas, "id", "nombre"), new { #class = "selectpicker", data_live_search = "true", title = "Area" })
</div>
<div class="form-group" style="align-self:center;">
#*<input type="submit" value="Filtrar" class="btn btn-primary" style="width:150px;" />*#
<button type="submit">Filtrar</button>
</div>
}
</fieldset>
<div id="tabless" class="card-body" style="">
<table id="table_id" class="display">
<thead>
<tr>
<th></th>
<th>ID Muestro</th>
<th>Area</th>
<th>Id Predio</th>
<th>Predio</th>
<th>Formulario</th>
<th>APLA</th>
<th>Total Parcelas</th>
</tr>
</thead>
<tbody>
#foreach (var item in ViewBag.muestreos)
{
<tr>
<td><input type="checkbox" id="cbox2" value="second_checkbox"></td>
<td>#item.IdMuestreo</td>
<td>#item.Area</td>
<td>#item.IdPredio</td>
<td>#item.NomPredio</td>
<td>#item.Formulario</td>
<td>#item.APLA</td>
<td>#item.TotalParcela</td>
</tr>
}
</tbody>
</table>
</div>
#section JavaScriptToFooter {
#Scripts.Render("https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js")
#Scripts.Render("https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/js/bootstrap-select.min.js")
<script>
$(document).ready(function () {
$('#table_id').DataTable();
$('.selectpicker').selectpicker();
});
</script>
#Scripts.Render("~/bundles/jqueryval")
}
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PlanificacionOperacional.Models;
using PlanificacionOperacional.Repository;
namespace PlanificacionOperacional.Controllers
{
public class MuestreoController : Controller
{
// GET: Muestreo
public ActionResult Index()
{
MuestreoRepository muestreo = new MuestreoRepository();
List<Muestreo> muestreos = muestreo.TraeMuestreo();
List<Filtro> predios = muestreo.TraePredios();
List<Filtro> zonas = muestreo.TraeZonas();
List<Filtro> areas = muestreo.TraeAreas();
ViewBag.muestreos = muestreos;
ViewBag.formularios = predios;
ViewBag.zonas = zonas;
ViewBag.areas = areas;
return View();
}
[HttpPost]
public ActionResult Filtrar(FiltroView model)
{
int predio = Convert.ToInt32(Request["predio"].ToString());
int zona = Convert.ToInt32(Request["zona"].ToString());
return View();
}
// GET: Muestreo/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: Muestreo/Create
public ActionResult Create()
{
return View();
}
// POST: Muestreo/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Muestreo/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: Muestreo/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Muestreo/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: Muestreo/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PlanificacionOperacional.Models
{
public class FiltroView
{
public int zona { get; set; }
public long predio { get; set; }
public int area { get; set; }
}
}
You are using MVC but you dont have any model. You will never be able to submit form without model. So for the start create a model
public ViewModel
{
public int ZonaId {get; set;]
public int AreaId {get;set;}
.... and so on
}
and after this view
#model ViewModel
......
#Html.DropDownListFor(model=>model.PredioId, new SelectList(ViewBag.formularios, "id", "nombre"), new { #class = "selectpicker", data_live_search = "true", title = "Predio" })
#Html.DropDownListFor(model=>model.ZonaId, new SelectList(ViewBag.zonas, "id", "nombre"), new { #class = "selectpicker", data_live_search = "true", title = "Zona" })
#Html.DropDownListFor(model=>model.AreaId, new SelectList(ViewBag.areas, "id", "nombre"), new { #class = "selectpicker", data_live_search = "true", title = "Area" })
.... and so on
action
public ActionResult Filtrar(ViewModel model)
{
int predioId = model.PredioId;
int zonaId = model.ZonaId;
.... your code
}
PS.
Get rid of all your viewbags. It looks very unprofessionaly and it is hard to mantain this kind of code. Include everything in the ViewModel.
public ActionResult Index()
{
MuestreoRepository muestreo = new MuestreoRepository();
var model=new ViewModel{
muestreos = muestreo.TraeMuestreo(),
predios = muestreo.TraePredios();
zonas = muestreo.TraeZonas();
areas = muestreo.TraeAreas();
....and so on
}
return View(model);
}

Generic View and Controller to avoid Duplicate Code in MVC

I have lots of models with same basic structure in my MVC project. So, I created a master class like below.
public class MasterTemplate
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Description { get; set; }
public DateTime? UpdatedOn { get; set; }
public string UpdatedBy { get; set; }
}
And I created all my model classes like below.
public class Industry : MasterTemplate
{
}
public class Caste : MasterTemplate
{
}
public class Gender : MasterTemplate
{
}
public class Qualification : MasterTemplate
{
}
public class BloodGroup: MasterTemplate
{
}
There are many more like this. Following is my code for IndustryController.
public class IndustryController : Controller
{
private ApplicationDbContext _context { get; set; }
private string UserId { get; set; }
public IndustryController()
{
_context = new ApplicationDbContext();
UserId = System.Web.HttpContext.Current.User.Identity.GetUserId();
}
public ActionResult Index(int id = 0)
{
Industry data = new Industry();
if (id > 0)
data = _context.Industries.SingleOrDefault(c => c.Id == id);
if (data == null)
data = new Industry();
return View("Industry", data);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Save(Industry data)
{
if (!ModelState.IsValid)
return View("Industry", data);
var record = _context.Industries.Where(c => c.Description.Trim().ToLower() == data.Description.Trim().ToLower() && c.Id != data.Id);
if (record.Count() > 0)
{
ModelState.AddModelError("Duplicate Industry", "Industry already exist");
return View("Industry", data);
}
Industry cm = new Industry();
if (data.Id >= 1)
{
cm = _context.Industries.SingleOrDefault(c => c.Id == data.Id);
cm.Description = data.Description;
cm.UpdatedOn = DateTime.Now;
cm.UpdatedBy = UserId;
}
else
{
cm = data;
_context.Industries.Add(cm);
}
_context.SaveChanges();
return RedirectToAction("Index", new { id = 0 });
}
And following is my code for IndustryView
#model Industry
#{
ViewBag.Title = "Industries";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h3>Industries Management</h3>
<div class="row">
<div class="col-md-4">
#using (#Html.BeginForm("Save", "Industry"))
{
#Html.ValidationSummary("Please correct the following")
#Html.HiddenFor(m => m.Id)
<div class="form-group">
<div>
#Html.LabelFor(m => m.Description)
#Html.TextBoxFor(m => m.Description, new { #class = "form-control", autocomplete = "off" })
#Html.ValidationMessageFor(m => m.Description)
</div>
</div>
#Html.AntiForgeryToken()
<button type="submit" class="btn btn-primary btn-sm">Save</button>
}
</div>
<div class="col-md-8">
<table class="table table-sm" id="mydata">
<thead>
<tr>
<th>
Industries
</th>
<th>
</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
#section scripts
{
#Scripts.Render("~/bundles/jqueryval")
<script>
$(document).ready(function () {
$("#mydata").DataTable({
ajax: {
url: "/api/get/industries",
dataSrc: ""
},
columns: [
{
data: "description"
},
{
data: "id",
render: function (data) {
var url = '#Url.Action("Index", "Industry", new { id = "__data__" })';
return 'Edit';
}
}
]
});
});
</script>
}
Now my problem is, code for controller and views for all the models in my project is almost similar. It is as above. So, I wanted to generalize them and create a single controller and view which can be used for all my other models. I am new to generics, tried the following code, but still not able to figure out the way forward. It is so confusing for me.
public interface IMaster
{
int Id { get; set; }
string Description { get; set; }
}
public class GenericController : Controller
{
private ApplicationDbContext _context { get; set; }
private string UserId { get; set; }
public GenericController()
{
_context = new ApplicationDbContext();
UserId = System.Web.HttpContext.Current.User.Identity.GetUserId();
}
public ActionResult Index(int id = 0)
{
IMaster data = null;
if (id > 0)
data = _context.Industries.SingleOrDefault(c => c.Id == id);
if (data == null)
data = new Industry();
return View("Generic", data);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Save(IMaster data)
{
if (!ModelState.IsValid)
return View("Generic", data);
var record = _context.Industries.Where(c => c.Description.Trim().ToLower() == data.Description.Trim().ToLower() && c.Id != data.Id);
if (record.Count() > 0)
{
ModelState.AddModelError("Duplicate Industry", "Industry already exist");
return View("Generic", data);
}
Industry cm = new Industry();
if (data.Id >= 1)
{
cm = _context.Industries.SingleOrDefault(c => c.Id == data.Id);
cm.Description = data.Description;
cm.UpdatedOn = DateTime.Now;
cm.UpdatedBy = UserId;
}
else
{
cm.Id = data.Id;
cm.Description = data.Description;
_context.Industries.Add(cm);
}
_context.SaveChanges();
return RedirectToAction("Index", new { id = 0 });
}
}
Can somebody guide me in right direction, need to create a generic controller and view for all the similar models in my project.
I have not run it, but I am pretty confident, that this should do the trick! Actually the only truly generic part is the controller. The other stuff is just the usual polymorphism. And thank you for the inspiration. It was fun thinking about such a solution. Maybe I'll build something similar in the future.
A word of caution: You will bind the name of your controllers to the name of each Model. Just be aware of this! There is a naming schema that must be kept or you break it.public class [ModelName]Controller : MasterController<ModelName>{}The ajax endpoints will end with the value of [PluralName](Read on in the View to know, what I mean.)
You will need an additional Property in the MasterTemplate. Ideally make it abstract, so you won't forget to implement it in the derived classes. This is for the Plural Name in the View's header and the ajax call in the View.
public abstract class MasterTemplate
{
[Key]
public int Id { get; set; }
public abstract string PluralName {get;}
[Required]
[StringLength(255)]
public string Description { get; set; }
public DateTime? UpdatedOn { get; set; }
public string UpdatedBy { get; set; }
}
Industry will then look like this
public class Industry: MasterTemplate
{
public override string PluralName => "Industries"
}
Make a truly generic Controller and derive all other Controllers from it like
public class IndustryController : MasterController<Industry>
{
//done everthing else is in the master :)
}
And here the generic MasterController<T>.
public class MasterController<T> : Controller where T : MasterTemplate, new()
{
private ApplicationDbContext _context { get; set; }
private string UserId { get; set; }
public MasterController()
{
_context = new ApplicationDbContext();
UserId = System.Web.HttpContext.Current.User.Identity.GetUserId();
}
public ActionResult Index(int id = 0)
{
T data = (id > 0)
? data = _context.Set<T>().SingleOrDefault(c => c.Id == id) ?? new T()
: new T();
return View("View", data);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Save(T data)
{
if (!ModelState.IsValid)
return View("View", data);
var record = _context.Set<T>().Where(c => c.Description.Trim().ToLowerInvariant() == data.Description.Trim().ToLowerInvariant() && c.Id != data.Id);
if (record.Count() > 0)
{
ModelState.AddModelError($"Duplicate {typeof(T).Name}", $"{typeof(T).Name} already exist");
return View("View", data);
}
if (data.Id >= 1)
{
T cm = _context.Set<T>().SingleOrDefault(c => c.Id == data.Id);
cm.Description = data.Description;
cm.UpdatedOn = DateTime.Now;
cm.UpdatedBy = UserId;
}
else
{
_context.Set<T>().Add(data);
}
_context.SaveChanges();
return RedirectToAction("Index", new { id = 0 });
}
Name the View "View" (or just the same, as you call it in the MasterController) and place it in the Shared Folder, for every controller to find it there.
#model MasterTemplate
#{
string name = Model.GetType().Name;
ViewBag.Title = name;
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h3>#Model.PluralName Management</h3>
<div class="row">
<div class="col-md-4">
#using (#Html.BeginForm("Save", name))
{
#Html.ValidationSummary("Please correct the following")
#Html.HiddenFor(m => m.Id)
<div class="form-group">
<div>
#Html.LabelFor(m => m.Description)
#Html.TextBoxFor(m => m.Description, new { #class = "form-control", autocomplete = "off" })
#Html.ValidationMessageFor(m => m.Description, $"{name} is required.", new { #class = "text-danger" })
</div>
</div>
#Html.AntiForgeryToken()
<button type="submit" class="btn btn-primary btn-sm">Save</button>
}
</div>
<div class="col-md-8">
<table class="table table-sm" id="mydata">
<thead>
<tr>
<th>
#(name)
</th>
<th>
</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
#section scripts
{
#Scripts.Render("~/bundles/jqueryval")
<script>
$(document).ready(function () {
$("#mydata").DataTable({
ajax: {
url: "/api/get/#(Model.PluralName)",
dataSrc: ""
},
columns: [
{
data: "description"
},
{
data: "id",
render: function (data) {
var url = '#Url.Action("Index", "#(name)", new { id = "__data__" })';
return 'Edit';
}
}
]
});
});
</script>
}

Retrieving ViewModel with multiple list objects once its posted

I have a viewmodel class like this:
public class ViewModel
{
public string VendorService { get; set; }
public List<ResponseView> responseList { get; set; }
}
Controller has get and post edit actions:
public ActionResult Edit(int? id)
{
List<ResponseView> resp = getResponseView(id); //get the list of ResponseView objects.
ViewModel view = new ViewModel();
view.responseList = resp;
view.VendorService = "Car Manufacturer";
return View(view);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ViewModel view)
{
if (ModelState.IsValid)
{
List<ResponseView> respList = new List<ResponseView>();
respList = view.responseList;
foreach(ResponseView resp in respList)
{
Debug.WriteLine(resp.Question);
}
return RedirectToAction("editConfirm");
}
return View("Index");
}
Edit.cshtml
#model Tools.Models.ViewModel
#{
List<Tools.Models.ResponseView> respList= Model.responseList as List<Tools.Models.ResponseView;
}
#foreach (var item in respList)
{
<div class="col-md-5">
#Html.EditorFor(model => item.Response, "" } })
#Html.ValidationMessageFor(model => item.Response, "", "" })
</div>
}
I am able to display the view and all the data in the View Model as required. But I am getting a null pointer reference when I try to retrieve the response in my post action, on foreach line below.
List<ResponseView> respList = new List<ResponseView>();
respList = view.responseList;
foreach(ResponseView resp in respList)
{
Debug.WriteLine(resp.Response);
}
You have to use for instead foreach . Please try this,
#for (int i = 0; i < Model.responseList.Count; ++i) {
<div>
#Html.EditorFor(model => Model.responseList[i].Response, "")
</div>

Getting Checkbox Value and Text in Controller

Model
public class AllControls
{
public List<Group> getChkItems { get; set; }
public bool chk { get; set; }
}
public class Group
{
public int ID { get; set; }
public string Name { get; set; }
}
Controller:
[HttpGet]
public ActionResult Index()
{
List<Group> li = new List<Group>()
{
new Group() { ID = 1, Name = "C#" },
new Group() { ID = 1, Name = "Asp.NET" },
new Group() { ID = 1, Name = "SQL" }
};
AllControls model = new AllControls();
model.getChkItems = li;
return View(model);
}
[HttpPost]
public ActionResult Index(AllControls e)
{
return View(e);
}
View:
#using (Html.BeginForm())
{
foreach (var x in #Model.getChkItems)
{
#Html.CheckBoxFor(m => m.chk, new { value = #x.ID }) #x.Name
<br />
}
<input type="submit" value="Submit" id="btn" />
}
How can I get the selected checkbox value and text in the controller?
Here goes my solution. Let your model be as shown below.
public class CheckboxModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool Checked { get; set; }
}
public class MainModel
{
public List<CheckboxModel> CheckBoxes { get; set; }
}
And let your Controller GET Action be as shown below.
public ActionResult GetDatas()
{
MainModel model = new MainModel();
var list = new List<CheckboxModel>
{
new CheckboxModel{Id = 1, Name = "India", Checked = false},
new CheckboxModel{Id = 2, Name = "US", Checked = false},
new CheckboxModel{Id = 3, Name = "UK", Checked = false}
};
model.CheckBoxes = list;
return View(model);
}
And POST Action be as shown below.
[HttpPost]
public ActionResult PostDatas(MainModel model)
{
return View(model);
}
The View should be as shown below.
#model WebApplication1.Controllers.MainModel
#using (Html.BeginForm("PostDatas","Home"))
{
for (var i = 0; i < Model.CheckBoxes.Count; i++)
{
<table>
<tr>
<td>
#Html.HiddenFor(m => Model.CheckBoxes[i].Id)
#Html.HiddenFor(m => Model.CheckBoxes[i].Name)
#Html.CheckBoxFor(m => Model.CheckBoxes[i].Checked)
</td>
<td>
#Html.DisplayFor(m => Model.CheckBoxes[i].Name)
</td>
</tr>
</table>
}
<input id="submit" type="submit" value="submit" />
}
View will be rendered as shown below.
When you select India and US and click on submit button, you will get POST parameters as below.

Partial View returning Null model ASP.NET MVC 4

Within my MainView, I was able to render all the "TaskComment"(model) using _GetForTask partial view. Then within my _GetForTask partial view, I was able to render _TaskCommentForm and successfull passed a new instance of TaskComment model. However, whenever I click the "Submit" button in the _TaskCommentForm partial view, it always returns null. What am I missing here? Thanks a lot.
"TaskComment" model
public partial class TaskComment
{
public int TaskCommentID { get; set; }
public Nullable<int> TaskID { get; set; }
public Nullable<int> AuthorID { get; set; }
public string Comment { get; set; }
public Nullable<System.DateTime> TimeStamp { get; set; }
public virtual Task Task { get; set; }
public virtual Employee Employee { get; set; }
}
Here's my "MainView"
#Html.Action("_GetForTask", "TaskComment", new { TaskID = Model.TaskID })
_GetForTask PartialView
#model IEnumerable<ProjectYesha.Models.TaskComment>
<div id="comments">
<ul>
#foreach (var taskComment in Model)
{
<li>#taskComment.Comment</li>
}
</ul>
#using (Html.BeginForm("_Submit", "TaskComment", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.Action("_TaskCommentForm", "TaskComment", new { TaskID = ViewBag.TaskID })
}
</div>
_TaskCommentForm PartialView
#model ProjectYesha.Models.TaskComment
#Html.HiddenFor(m=> m.TaskCommentID)
#Html.HiddenFor(m=> m.TaskID)
#Html.HiddenFor(m=> m.AuthorID)
#Html.HiddenFor(m=> m.TimeStamp)
#Html.HiddenFor(m=> m.Employee)
#Html.HiddenFor(m=> m.Task)
<div>
#using (Html.BeginForm())
{
#Html.EditorFor(m => m.TaskID)
#Html.EditorFor(m => m.Comment)
<input type="submit" value = "Submit" />
}
</div>
TaskCommentController
public PartialViewResult _GetForTask(Int32 taskID)
{
ViewBag.TaskID = taskID;
List<TaskComment> comments = db.TaskComments.Where(c => c.TaskID == taskID).ToList();
return PartialView("_GetForTask", comments);
}
[ChildActionOnly()]
public PartialViewResult _TaskCommentForm(Int32 taskID)
{
TaskComment comment = new TaskComment()
{
TaskID = taskID ,
};
return PartialView("_TaskCommentForm", comment);
}
[HttpPost]
[ValidateAntiForgeryToken()]
public PartialViewResult _Submit(TaskComment comment)
{
db.TaskComments.Add(comment);
db.SaveChanges();
List<TaskComment> comments = db.TaskComments.Where(c => c.TaskID == comment.TaskID).ToList();
ViewBag.TaskID = comment.TaskID;
return PartialView("_GetForTask", comments);
}

Categories

Resources