c# - Show List and Submit form on same view in MVC -
i have class name comment follow
public class comment { public int id { get; set; } public string name { get; set; } public string coment { get; set; } }
what i'm trying , want show list of comments , form add comment on same view(index), have done, far i'm unable hint
, index view
@model ienumerable<guestbookentryapp.models.comment> <h2>index</h2> <div id="commentlist"> <table> <tr> <th>name</th> <th>comments</th> </tr> @foreach (var obj in model) { <tr> <td>@obj.name</td> <td>@obj.coment</td> </tr> } </table> </div> <br /> <div id="commentbox"> @html.partial("~/views/comments/_addcomment.cshtml", new viewdatadictionary { model = new guestbookentryapp.models.comment() }) </div>
but here i'm unable hint @html.labelfor(x => x.name)
controller
public class commentscontroller : controller { guestbookcontext db = new guestbookcontext(); // dbcontxt class public actionresult index() { ilist<comment> _comment = db.comments.tolist(); return view(_comment); } public partialviewresult addcomment() { return partialview("_addcomment"); } public partialviewresult addcomment(comment _comment) { db.comments.add(_comment); db.savechanges(); return redirecttoaction("index"); } }
is there other way this. want
create view model properties existing comments , new comment
public class commentvm { public ienumerable<comment> existingcomments { get; set; } public comment newcomment { get; set; } }
view
@model yourassembly.commentvm .... @foreach (var obj in model.existingcomments) { ... } @using (ajax.beginform("addcomment", .....})) { @html.labelfor(x => x.newcomment.name) ....
and adjust controller add bind.prefix
property
public actionresult addcomment([bind(prefix="newcomment")]comment _comment) { ....
Comments
Post a Comment