如何在表格中插入数据?

时间:2014-08-11 06:27:34

标签: c# sql asp.net-mvc asp.net-mvc-4

我需要从一个内部有foreach循环的表中插入数据。我曾经和webforms一起工作,所以我是mvc的新人。我总是在使用gridview控件的webforms中遇到这个场景,并且只是实现了findcontrol命令,它工作正常。但是在mvc中,我几乎无法得到解决方案。我已经在线搜索,但无法找到符合我对此类问题的需求的文章。到目前为止,我所得到的是,如果我从表的第一行插入数据,它将插入记录,但如果我从第二行,第三行插入它们,那么第四行,它将不再插入记录进入我的数据库表。如何使这完美起作用? 继承我的模型,视图和控制器,以帮助您解决问题。感谢...

模型

public class CommentModel
    {
        public int Id { get; set; }

        [Required(ErrorMessage="Don't miss to put your name.")]
        public string name { get; set; }

       [Required(ErrorMessage = "Don't leave your comments empty.")]
        public string comment { get; set;}


    }

    public class ReplyModel
    {
        public int idrep { get; set; }
        public string namerep { get; set; }
        public string reply { get; set; }
    } 

    public class CreateViewModel
    {
        public CommentModel CreateComment { get; set; } // this line is optional
        public ReplyModel CreateReply { get; set; }
        public List<CommentModel> Comments { get; set; }
        public List<ReplyModel> Replies { get; set; }
    }


Repository:

  public class ReplyRepository
    {
          private ProfileDataContext3 Reprepository;

          public ReplyRepository()
        {
            Reprepository = new ProfileDataContext3();
        }

          public IEnumerable<ReplyModel> GetAllComments()
          {
              List<ReplyModel> profiles = new List<ReplyModel>();
              var prof = from profile in Reprepository.RepTabs
                         orderby profile.Id descending
                         select profile;
              var user = prof.ToList();
              foreach (var item in user)
              {
                  profiles.Add(new ReplyModel()
                  {
                      idrep = item.Id,
                      namerep = item.Name,
                      reply = item.Replies

                  });
              }
              return profiles;
          }
          //declaring methods for inserting records
          public void InsertReply(ReplyModel profile)
          {
              var details = new RepTab()
              {
                  Id=profile.idrep,
                  Name = profile.namerep,

                  Replies = profile.reply

              };

              Reprepository.RepTabs.Add(details);
              Reprepository.SaveChanges();
          }

    }

控制器

public ActionResult PostComment()
        {

            var vModel = new CreateViewModel();

            vModel.Comments = comrepository.GetAllComments().ToList();
            vModel.Replies = replyrepository.GetAllComments().ToList();
            return View(vModel); 
        }

        [HttpPost]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult PostComment(CommentModel com,string butname, ReplyModel rep)
        {

           switch(butname)
            {
                case "Post Comments":
            if (ModelState.IsValid)
            {
                comrepository.InsertComment(com); //this is to insert the records


            }
            //this is to display the records inserted
            var vModel = new CreateViewModel();

            vModel.Comments = comrepository.GetAllComments().ToList();
            vModel.Replies = replyrepository.GetAllComments().ToList();
            return View(vModel); 

                case "Post Reply":
                    if (ModelState.IsValid)
            {
                replyrepository.InsertReply(rep); //this is to insert the records


            }
            //this is to display the records inserted
            var vModel2 = new CreateViewModel();

            vModel2.Comments = comrepository.GetAllComments().ToList();
            vModel2.Replies = replyrepository.GetAllComments().ToList();
            return View(vModel2); 

                default:
            return null;

           } 

        }

查看

@model  MyFirstMVCApp.Models.CreateViewModel

@{
    ViewBag.Title = "PostComment";
}

<h2>Post Comment</h2>

<br />
@using (Html.BeginForm("PostComment", "Profile", FormMethod.Post, new { }))
{
    @Html.ValidationSummary("Unable to Post Comment. Please correct the errors and try again...")

    <fieldset>
        <legend>CommentModel</legend>

        <div class="editor-label">
           <label for="name">Name</label>
        </div>
        <div class="editor-field">

       <input type="text" id="name" name="name" />
       <span class="field-validation-valid" data-valmsg-for="name" data-valmsg-replace="true"></span>
        </div>

        <div class="editor-label">
            <label for="comment">Post your Comment here:</label>
        </div>
        <div class="editor-field">
      <textarea id="comment" name="comment" style="width:500px;height:100px;resize:none" ></textarea>
      <span class="field-validation-valid" data-valmsg-for="comment" data-valmsg-replace="true"></span>
        </div>

        <p>
            <input type="submit" value="Post Comments" name="butname" />
             @Html.ActionLink("See Comments", "DisplayComment")
        </p>
        <br />

    </fieldset>
}

   <br />
    <h2>Comments</h2>
     <br />

       @using (Html.BeginForm("PostComment", "Profile", FormMethod.Post, new { }))
{   
      <table>     
@foreach (var item in Model.Comments)
{
    <tr>
        <td>
        <div class="editor-field" style="display:none;margin-bottom:10px;margin-top:10px">

           @Html.TextBoxFor(m => m.CreateComment.Id)
        </div>

         <div style="font-weight:bold;">  @Html.DisplayFor(modelItem => item.name) </div> 

  <p style ="margin-top:0px;margin-bottom:0px; border-radius: 4px 4px 4px 4px; max-width :500px; min-height :5px;  display :block; background-color: #CCCCFF">  @Html.DisplayFor(modelItem => item.comment) </p>
  <p style="margin-top:2px;margin-bottom:0px"> <input type="button" id="like" name="like" value="Like" style="color:blue;border:0px;background-color:inherit;cursor:pointer" /> <input type="button" id="Reply" name="Reply" value="Replie(s)" style="color:blue;border:0px;background-color:inherit;cursor:pointer" /></p>

          <div id="divrep" style="position:relative;left:50px; overflow:auto;margin-top:0px">
             <table>
              @foreach (var item2 in Model.Replies)
              {
                 <tr>
                     <td>
                     <p style ="margin-top:0px;margin-bottom:0px; border-radius: 4px 4px 4px 4px; max-width :445px; min-height :5px;  display :block; background-color: #CCCCFF;">@Html.DisplayFor(modelItem => item2.reply)  </p>
                           <br />


                   </td>
                 </tr>
              } 
            </table>


         </div> 
             <input type="text" id="idrep" name="idrep" value="@Html.DisplayFor(modelItem=>item.Id)" />
       <span class="field-validation-valid" data-valmsg-for="idrep" data-valmsg-replace="true"></span>
                         <br />
           <input type="text" id="namerep" name="namerep" />
       <span class="field-validation-valid" data-valmsg-for="namerep" data-valmsg-replace="true"></span>
                         <br />
              <textarea id="reply" name="reply" style="width:500px;height:100px;resize:none" ></textarea>
      <span class="field-validation-valid" data-valmsg-for="reply" data-valmsg-replace="true"></span>

    <br />
           <input type="submit" value="Post Reply" name="butname" />

        </td>


    </tr>

}

</table>


      }
<br />
<br />
<div>
    @Html.ActionLink("Back to List", "Index")
</div>



@section scripts
{
     <script type ="text/jscript"  src="JQuery/jquery-1.4.3.min.js"> 
</script>
    <script type="text/javascript">

    $('body').keypress(function(e) {
       if (e.which == 13) {
          $("input[value='Post Comments']").trigger('click');
       }
    });

        </script>
    }

1 个答案:

答案 0 :(得分:0)

问题在于控件的命名,你有多个具有相同名称的控件,而DefaultModelBinder只会绑定第一个控件(即第一行)而忽略其余控件。我建议使用jquery发布新注释的另一种方法,避免每次都刷新页面。

查看

...
@using (Html.BeginForm()) {
  <div>
    @Html.LabelFor(m => m.CreateComment.Name)
    @Html.TextBoxFor(m => m.CreateComment.Name)
    @Html.ValidationMessageFor(m => m.CreateComment.Name)
    // repeat for CreateComment.Comment property
    <input type="submit" id="post-comment" value="Submit Comment" />
  </div>
}
...

脚本

$('form').submit(function(e) {
  e.preventDefault(); // prevent submission
}

$('#post-comment').click(function() {
  // get values for postback
  var inputs = $(this).closest('div').find('input');
  var name = inputs.first().val();
  var comment = inputs.last().val();
  var url = '@Url.Action("PostComment", "Profile")';
  $.post(url, { Name: name, Comment: comment }, function(data) {
    if(data) {
      inputs.val(''); // clear existing inputs
      // create a new element for the comment and add to the DOM, for example
      var para = $('div></div>).text(comment).appendTo(something);
    } else {
      // display an error message
    }
  }
}

并添加一个类似的脚本来发布回复,除了使用类名而不是按钮的id,所以没有重复的ID

控制器

[HttpPost]
public ActionResult PostComment(CommentModel model)
{
  // save the comment and if successful
    return Json(true);
  else
    return null;
}

对于回复回复,在您的foreach循环中,为相应的注释ID添加隐藏的输入,并将其包含在数据中以回发到单独的操作

[HttpPost]
public ActionResult PostReply(ReplyModel model)
{
  ...