如何在Razor View中将onclick事件添加到单选按钮

时间:2014-09-01 22:54:00

标签: javascript html asp.net-mvc razor radio-button

我有这个观点。没关系,我想在其中添加:onclick="javascript:SubmitClick(@Model.id, answer.Id);"来定义RadioButtons。

@model WebApplication2.Models.Question
<div>
    @Html.HiddenFor(x => x.Id)
    <h3> @Model.QuestionText </h3>
    @foreach (var answer in Model.Answers) {
        <p>
            @Html.RadioButtonFor(b => b.SelectedAnswer, answer.Id)  @answer.AnswerText
        </p>
    }
</div>

问题和答案是看起来像这样的模型。

 public class Question {
        public int Id { set; get; }
        public string QuestionText { set; get; }
        public virtual ICollection<Answer> Answers { set; get; }
        public string SelectedAnswer { set; get; } //this field is SET after clicking the radio button, I don't need this field ant this behaviour

    }
    public class Answer {
        public int Id { set; get; }
        public string AnswerText { set; get; }
    }

据我所知b => b.SelectedAnswer@Html.RadioButtonFor中的此表达式会在点击后设置SelectedAnswer类中的字段Question。我不需要我只需要同时选择foreach循环中的一个单选按钮并单击它们调用onclick="javascript:SubmitClick(@Model.id, answer.Id);"。此外,它可以以过时的方式完成,只是为了使其工作。

屏幕有助于查明视图的外观:

enter image description here

1 个答案:

答案 0 :(得分:0)

观点:

@model WebApplication2.Models.Question
<div>
    @Html.HiddenFor(x => x.Id)
    <h3> @Model.QuestionText </h3>
    <form action="">
        @foreach (var answer in Model.Answers) {
            <p>
                <input type="radio" onclick="javascript:SubmitClick(@Model.Id, @answer.Id);">@answer.AnswerText<br>

            </p>
        }
    </form>
</div>

脚本函数位于Person的强类型视图中:

 function SubmitClick(qid, aid) {
        var url = '@Url.Action("SubmitSurvey", "Person")';

        $.post(url, { questionId: qid, answerId: aid, personId:@Model.Id }, function (data) {
            alert('questionId: ' + qid + ' answerId ' + aid);
        });
    }

脚本调用的方法

  public void SubmitSurvey(int questionId, int answerId, int personId) {

            System.Diagnostics.Debug.WriteLine("UPDATING DATABASE " + "Selected personId: " + personId);

        }