我添加了一个视图组件。它以共享布局呈现。 我需要用户可以更改选择选项。 更改后,必须在控制器上执行代码。
我尝试了onchange =“ myfunction()”。我的工作职责。
@model myapp.Web.Models.Scheduling.ScheduleNavModel
<form class="form-inline">
<div class="form-group">
<label asp-for="Id"></label>
<select asp-for="Id" asp-items="@(new SelectList(Model.SerialSchedules, "Id", "Name"))" onchange="func()" class="form-control basic-select2"></select>
<span asp-validation-for="Id" class="text-danger"></span>
</div>
</form>
@section scripts {
<script>
function func() {
alert('hi');
}
</script>
}
还请注意,我需要onchnage事件在.net core中执行代码。
public IViewComponentResult Invoke()
{
var model = new ScheduleNavModel();
var activeSerialId = Convert.ToInt64(HttpContext.Session.GetString("banner_serial"));
if (activeSerialId != 0)
{
model.SerialSchedules= _scheduleService.GetBySerial(activeSerialId).Select(x => x.ToModel()).ToList();
}
return View(model);
}
@model Celluloid.Web.Models.Scheduling.ScheduleNavModel
<form class="form-inline">
<div class="form-group">
<label asp-for="Id"></label>
<select asp-for="Id" asp-items="@(new SelectList(Model.SerialSchedules, "Id", "Name"))" class="form-control basic-select2"></select>
<span asp-validation-for="Id" class="text-danger"></span>
</div>
</form>
我希望select的onchange方法必须在组件发布中呈现一些代码。
[post]
public IViewComponentResult Invoke(ScheduleNavModel model)
{
my code here
}
答案 0 :(得分:1)
如果仅在ViewComponent的视图中添加js代码,则该代码无法直接工作,您需要将其放在父视图中。
此外,ViewComponent没有POST
方法,我建议您可以使用Ajax将表单数据发送到另一个控制器中的操作。
以下是您可以参考的演示:
ViewComponent视图:
<form class="form-inline" id="myform">
<div class="form-group">
<label asp-for="Id"></label>
<select asp-for="Id" asp-items="@(new SelectList(Model.SerialSchedules, "Id", "Name"))" onchange="func()" class="form-control basic-select2"></select>
<span asp-validation-for="Id" class="text-danger"></span>
</div>
</form>
_Layout.cshtml:
<div id="root">
@await Component.InvokeAsync("NameOfYourComponent")
</div>
<script>
function func() {
$.ajax({
type:'POST',
url: '/Home/TestView',
data:$('#myform').serialize(),
success: function (data) {
//do what you would like to do
//$("#root").html(data.Value);//fill the result view to the div whose id is "root"
}
})
}
</script>
HomeController:
[HttpPost]
public ViewComponentResult TestView(ScheduleNavModel model)
{
//your logic
return ViewComponent("NameOfYourComponent");
//or return ViewComponent("PriorityList",new { model = model}); if you need to pass some parameters
}