asp.net - Model mismatch error when posting form -
i working on simple image upload site in users have ability post comments on images uploaded site, whenever posting comment given error :
the model item passed dictionary of type '<>f__anonymoustype1`1[system.int32]', dictionary requires model item of type 'silkmeme.models.meme'.
i know has model being defined @ top of view being different 1 sending post request i'm not entirely sure how fix it
view
@model silkmeme.models.meme .... @using (html.beginform("comment", "memes", new { id = model.silkid })) { <label for="thought">thoughts?</label> <input type="text" name="thought"/> <label for="rating">rating?</label> <input name="rating" type="range" min="0" max="10" step="1" /> <input type="submit" value="post thoughts" /> } <div class="thoughts"> @foreach (var c in viewbag.thoughts) { <p>- @c.thoughtwords , @c.thoughtrating / 10 meme</p> } </div>
controller
public actionresult details(int? id) { var thoughts = comment in db.thoughts comment.silkid == id select comment; viewbag.thoughts = thoughts; if (id == null) { return new httpstatuscoderesult(httpstatuscode.badrequest); } meme meme = db.memes.find(id); if (meme == null) { return httpnotfound(); } return view(meme); } [httppost] public actionresult comment(int id) { int thoughtid = (from m in db.thoughts select m).orderbydescending(e => e.thoughtid).firstordefault().thoughtid + 1; if (request["thought"].tostring() != "") { thought thought = new thought() { thoughtid = thoughtid, silkid = id, meme = db.memes.find(id), thoughtwords = request["thought"], thoughtrating = int32.parse(request["rating"]) }; db.thoughts.add(thought); } return view("details", new { id = id }); }
this line.
return view("details", new { id = id });
it passing anonymous object id property view typed meme
type , expects object of meme
class.
if save data successfully, ideally,you should redirect action (following prg pattern)
[httppost] public actionresult comment(int id) { int thoughtid = (from m in db.thoughts select m) .orderbydescending(e => e.thoughtid).firstordefault().thoughtid + 1; if (request["thought"].tostring() != "") { thought thought = new thought() { thoughtid = thoughtid, silkid = id, meme = db.memes.find(id), thoughtwords = request["thought"], thoughtrating = int32.parse(request["rating"]) }; db.thoughts.add(thought); db.savechanges(); } return redirecttoaction("details", new { id=id }); }
also, recommend using mvc modelbinding read submitted form data. find ton of examples on stackoverflow that. when using modelbinding, can return posted view model view (with error message if needed) , validationsummary /validationmessgefor helper methods can show error message user needed.
Comments
Post a Comment