我是MVC 5,Razor的新手,我对这个问题非常困惑。我正在创建一个JQuery draggable / droppable页面,用户可以将项目从“可用项目”无序列表拖到“选定项目”无序列表中。
当项目被删除时,我使用javascript将列表项添加到ul。单击表单的提交按钮并提交表单时,我通过调用event.preventDefault()方法停止发生默认提交。然后我循环遍历所选项的所有id,将它们放入一个数组中,然后将它们发布到控制器方法中。这一切都运作良好。
如果发生错误,我想在新表列的响应页面顶部呈现错误消息。它不会被渲染(它不在页面源中)。需要一段时间才弄明白,但看起来它是导致它的event.preventDefault()方法 - 如果我把它拿出来,它会显示错误信息,但当然控制器方法被调用两次。
非常感谢任何帮助,为什么会发生这种情况。
更新:我添加了应该编译并重现问题的代码:
- 运行它,并将“输入数据集名称:”文本框保留为空(这是一个错误)
- 单击“添加数据集”按钮,您将看不到任何错误消息
- 在表单提交javascript函数中注释掉event.preventDefault()
- 运行它,做同样的事情,你会看到错误信息(红色字体)。
类别:
public class DataSourceField
{
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private string text;
public string Text
{
get { return text; }
set { text = value; }
}
}
型号:
public class DataSetMaintModel : ModelBase
{
public int[] InsertSelFields { get; set; }
public List<DataSourceField> AvailColumnList { get; set; }
public string ExceptionMsg { get; set; }
public string DataSetNameInsert { get; set; }
public DataSetMaintModel()
{ }
}
Razor查看:
@using TOTestMgmt
@model TOTestMgmt.Models.DataSetMaintModel
@{
ViewBag.Title = "CM Lot Search";
}
@MvcHtmlString.Create("<table border=\"1\" style=\"margin:20px;\">")
@MvcHtmlString.Create("<tr><td style=\"width:45px;\" class=\"MainLayoutHeader\">")
@MvcHtmlString.Create("Data Set Maintenance</td>")
@if (Model != null && Model.ExceptionMsg != null)
{
<td class="ErrorMsg" style="padding-left:15px; padding-top:8px;" colspan="4">
@Html.DisplayFor(model => model.ExceptionMsg)
</td>
}
@MvcHtmlString.Create("</tr>")
@MvcHtmlString.Create("<tr><td colspan=\"3\" class=\"LayoutColumn\" style=\"width:")
@MvcHtmlString.Create("vertical-align:top; padding-top:6px;\">")
@MvcHtmlString.Create("<div class=\"OuterDivThinBorder\">")
@MvcHtmlString.Create("<table border=\"1\" class=\"ContentTable\" style=\"margin-bottom:10px;\" height=\"400px\" width=\"100%\">")
@MvcHtmlString.Create("<tr height=\"30px\"><td class=\"SmallHeaderColor\" colspan=\"2\">")
@MvcHtmlString.Create("<b>Add New Data Set</b></td></tr>")
@using (Html.BeginForm("InsertDataSet", "DataSetMaint", FormMethod.Post))
{
if (Model != null)
{
@MvcHtmlString.Create("<tr height=\"25px\"><td class=\"LeftIndent\" style=\"padding-top:8px; vertical-align: top; width:30%;\" >")
@MvcHtmlString.Create("Enter Data Set Name:<br>")
@Html.TextBoxFor(model => model.DataSetNameInsert, new { @style = "width:97%;", @class = "LeftIndent" })
@MvcHtmlString.Create("</td>")
@MvcHtmlString.Create("<td align=\"left\" style=\"padding-left:15px; vertical-align:bottom; width:30%;\">")
@MvcHtmlString.Create("<input class=\"GreyButton\" type=\"submit\" value=\"Add Data Set\" name=\"InsertDataSetSubmit\"/></td></tr>")
@MvcHtmlString.Create("<tr height=\"25px\"><td style=\"padding-top:3px;\" class=\"LeftIndent\" width=\"90px\" colspan=\"3\">")
@MvcHtmlString.Create("Available Fields</td></tr>")
@MvcHtmlString.Create("<tr height=\"300px\"><td style=\"vertical-align:top;\" class=\"LeftIndent\">")
<div id="AvailColsDiv">
<ul style="margin-left:-35px;">
@foreach (DataSourceField item in Model.AvailColumnList)
{
<li class="dragclass" id="@item.Id" title="@item.Text">@item.Text</li>
}
</ul>
</div>
@MvcHtmlString.Create("</td><td style=\"vertical-align:top; width:40%;\" class=\"LeftIndent\">")
<div id="SelectedColsDiv">
<ul style="margin-left:-20px;">
@*<li class="placeholder">Add your items here</li>*@
</ul>
</div>
@MvcHtmlString.Create("</td></tr>")
}
}
@MvcHtmlString.Create("</table></div></td></tr></table>")
@section JavaScript {
<script src="~/Scripts/MyJavaScript.js"></script>
}
使用Javascript:
$(function () {
$("#AvailColsDiv li").draggable({
appendTo: "body",
helper: "clone",
refreshPositions: true
});
$("#SelectedColsDiv").droppable({
accept: ":not(.ui-sortable-helper)",
drop: function (event, ui) {
var id = $(ui.draggable).attr('id');
$(this).find(".placeholder").remove();
$('<li class="dropclass droplistitem" id="' + id + '" title="' + ui.draggable.text() + '"></li>').text(ui.draggable.text()).appendTo(this);
}
}).sortable({
items: "li:not(.placeholder)",
sort: function () {
$(this).removeClass("ui-state-default");
}
});
});
$('form').on('submit', function (event) {
//Stop the default submission
event.preventDefault();
var ids = [];
$('.droplistitem').each(function (index, value) {
var id = $(value).prop('id');
ids.push(id);
});
$.post(
'/DataSetMaint/InsertDataSet',
{
requestModel: {
InsertSelFields: ids,
DataSetNameInsert: $('#DataSetNameAdd').val()
},
Ids: ids
}
);
});
控制器方法:
public class DataSetMaintController : Controller
{
[HttpGet]
public ActionResult DataSetMaintAdd(int Id = 1, string successMsg = null)
{
DataSetMaintModel responseModel = null;
try
{
responseModel = new DataSetMaintModel();
responseModel.AvailColumnList = PopulateAvailList();
return View(responseModel);
}
catch (Exception ex)
{
responseModel.ExceptionMsg = ex.Message;
return View("DataSetMaintAdd", responseModel);
}
}
[HttpPost]
public ActionResult InsertDataSet(DataSetMaintModel requestModel, int[] Ids)
{
DataSetMaintModel responseModel = new DataSetMaintModel();
try
{
//Validate required values
if (String.IsNullOrWhiteSpace(requestModel.DataSetNameInsert))
{
responseModel.AvailColumnList = PopulateAvailList();
throw new Exception("Please Enter Data Set Name");
}
responseModel.DataSetNameInsert = requestModel.DataSetNameInsert;
responseModel.AvailColumnList = PopulateAvailList();
return View("DataSetMaintAdd", responseModel);
}
catch (Exception ex)
{
ModelState.Remove("ExceptionMsg");
responseModel.ExceptionMsg = ex.Message;
return View("DataSetMaintAdd", responseModel);
}
}
public List<DataSourceField> PopulateAvailList()
{
List<DataSourceField> availColumnList = new List<DataSourceField>();
DataSourceField field = new DataSourceField { Id = 1, Text = "Item 1" };
availColumnList.Add(field);
field = new DataSourceField { Id = 2, Text = "Item 2" };
availColumnList.Add(field);
return availColumnList;
}
}
CSS:
#AvailColsDiv {
float: left;
background-color: #E5E4E2;
border-radius: 5px;
overflow: visible;
width: 290px;
height: 450px;
margin: 5px;
overflow-y: scroll;
overflow-x: hidden;
}
#AvailColsDiv ul{
height: 750px;
float: left;
}
#SelectedColsDiv {
float:left;
background-color: #E5E4E2;
border-radius: 5px;
overflow:visible;
width: 290px;
height: 450px;
margin: 5px;
max-height: 450px;
overflow-y: scroll;
}
.dragclass {
background-color: #ffff99;
border: 1px solid Black;
border-radius: 5px;
padding: 5px;
margin: 10px;
width: 220px;
list-style-type:none;
}
.dropclass {
background-color: #ffff99;
border: 1px solid Black;
border-radius: 5px;
padding: 5px;
margin: 10px;
width: 220px;
list-style-type:none;
}
#AvailColsDiv li, #SelectedColsDiv li {
cursor: pointer;
}
.ErrorMsg {
font-size: 14px;
font-weight: 600;
color: red;
}