Мне нужно вставить данные из таблицы с внутренней петлей foreach. Я работал с веб-формами, поэтому я новичок в mvc. Я всегда сталкивался с этим сценарием в webforms, используя gridview control, и просто реализую команду findcontrol, и она отлично работает. Но в mvc я едва мог получить решения, как это сделать. Я уже выполняю поиск в Интернете, но не могу найти статей, которые соответствуют моим потребностям в этом типе проблем. Пока что у меня есть, если я вставляю данные из первой строки таблицы, он будет вставлять запись, но если я вставлю их из второго, третьего и четвертого, то он больше не будет вставлять записи в мои таблица базы данных. Как я могу сделать это отлично? Heres моя модель, просмотр и контроллер, чтобы помочь вам решить проблему. Спасибо ...Как вставить данные в таблицу?
Модель
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>
}
трудно следовать вашему описанию проблемы. Можете ли вы упростить его (нарушите утверждения в параграфе, выделите код, где у вас проблемы, и т. Д.)? – SBirthare
Если вы посмотрите на представление, вы можете увидеть там часть, где вы можете отправить ответ, в таблице, в которой есть цикл foreach. Моя проблема заключается в том, что он не сохранит данные, если вы вводите их во вторую строку и так далее таблицы. – timmack
Правильно ли я предполагаю, что вы показываете коллекцию комментариев, и для каждого комментария вы показываете свою коллекцию ответов и хотите, чтобы пользователи могли (1) добавлять новый комментарий и (2), чтобы быть в состоянии добавить новый ответ для каждого комментария? –