我已经开始编写JavaScript来处理DropDownListFor的更改,但它错了。我不想在变更上提交表格。我想从DropDownList中选择一个值,显示列表已被更改但不提交表单,因为表单仍有其他控件需要填写。如何使用jQuery的JavaScript执行此操作?是否必须进行回发?
这是我编写的JavaScript代码和表单:
<script type="text/javascript">
$(function () {
$('#DropDownListForId').change(function () {
$('form#myForm').submit();
});
});
</script>
<div class="container" style="padding-top: 20px;">
@Html.LabelFor(x => x.CurrentPub)
@Html.TextBoxFor(x => x.CurrentPub)
<br/>
<br/>
<div class="form-holder">
@using (Html.BeginForm(null, null, FormMethod.Post, new {id = "myForm"}))
{
<div class="row">
<div class="col-xs-6">
<label>UI Element:</label>
@Html.DropDownListFor(m => m.SelectedUIItem, Model.UIItems, new {@id = "DropDownListForId"})
</div>
<div class="col-xs-6">
@Html.LabelFor(m => m.UseWholeMarkup)
@Html.CheckBoxFor(m => m.UseWholeMarkup)
</div>
</div>
}
<div class="row">
<div class="col-xs-9">
@Html.LabelFor(m => m.HTMLMarkupCode)
@Html.TextAreaFor(m => m.HTMLMarkupCode, new { rows = "10", cols = "100" })
</div>
</div>
<div class="row">
<button class="btn btn-default" type="submit">Submit</button>
</div>
</div>
</div>
这是ViewModel:
public class UIItemsViewModel
{
[Display(Name = "Current Pub: ")]
public string CurrentPub { get; set; }
// DropDownList
public string SelectedUIItem { get; set; }
// public IEnumerable<string> SelectedUIItem { get; set; }
public IEnumerable<SelectListItem> UIItems { get; set; }
// Checkbox
[DisplayName("Use Whole Markup ")]
public bool UseWholeMarkup { get; set; }
// Text Area - Whole Markup
[Display(Name = "HTML Markup Code: ")]
public string HTMLMarkupCode { get; set; }
public string HeaderText { get; set; }
public string HeaderFColor { get; set; }
public string HeaderBColor { get; set; }
public string LogoURL { get; set; }
public string FooterFColor { get; set; }
public string FooterText { get; set; }
public string FooterBColor { get; set; }
public string BodyText { get; set; }
public string BodyFColor { get; set; }
public string BodyBColor { get; set; }
}
答案 0 :(得分:0)
在表单中添加一个onsubmit:
@using (Html.BeginForm(null, null, FormMethod.Post, new {id = "myForm", onsubmit="return CheckForm()}))
然后添加一个javascript函数以查看是否所有内容都已填写:
function CheckForm() {
var ret = true;
if (document.getElementById("DropDownListForId").selectedIndex == 0) {
ret = false;
}
// Add whatever other logic or checks you need
return ret;
}
答案 1 :(得分:0)
简而言之 - 听起来你想要下拉列表(或选择)的正常行为。所以删除javascript,它会按预期工作,不是吗?
关于评论 - 获取价值和文字。您没有告诉我们您想要显示的位置。 “之前”还不够。请尝试使用此javascript,也许您可以根据自己的需要进行编辑:
<script type="text/javascript">
$(function () {
$('#DropDownListForId').change(function () {
alert('This is the selected value: ' + $(this).val() + ' and text: ' + $("option:selected", $(this)).text());
//this should, hopefully, update the label with the current selected text. I doubt this is wanted, but it shows what could be done.
$(this).parent().find('label').html($("option:selected", $(this)).text());
});
});
</script>