0

I have a button and a script:

   <script>
   function SubmitClick () {
        var pid = $(this).data('personid');
        var sid = $(this).data('surveyid');
        var url = '@Url.Action("SubmitSurvey", "Person")';
        $.post(url, { personid: pid, surveyid: sid }, function (data) {
            alert('updated');
        });
    };
</script>

When I click the button the script is not run/called/invoked. How to make this button invoke this script?

Full view _Survey1.html this is PartialView:

<script>
   function SubmitClick () {
        var pid = $(this).data('personid');
        var sid = $(this).data('surveyid');
        var url = '@Url.Action("SubmitSurvey", "Person")';
        $.post(url, { personid: pid, surveyid: sid }, function (data) {
            alert('updated');
        });
    };
</script>

@using WebApplication2.Models
@model   System.Tuple<Person, List<Survey>>

<hr />
<h1>Surveys</h1>
<input type="button" id="Coll" value="Collapse" onclick="javascript:CollapseDiv()" />
@*<p>
        Number of Surveys: @Html.DisplayFor(x => Model.Item2.Count)
    </p>*@

@{int i = 1;}
@foreach (var survey in Model.Item2) {
    using (Html.BeginForm()) {
        <h2>Survey @(i)</h2>
        <p />
        @Html.EditorFor(x => survey.Questions)


        <button class='mybutton' type='button' data-personid="@Model.Item1.Id" data-surveyid="@survey.Id" onclick="javascript:SubmitClick()">Click Me</button>
    }
    i++;
    <hr style="background-color:rgb(126, 126, 126);height: 5px" />
}
<hr />

The SubmitSurvey method in PersonController:

 public void SubmitSurvey(int personId, int surveyId) {
        System.Diagnostics.Debug.WriteLine("UPDATING DATABASE");

    }

The result is that after clicking the button I get error saying that SubmitClickhaven't been found:

enter image description here

Details.cshtml (the _Survey1.cshtml) is rendered inside of it.

@model WebApplication2.Models.Person

@{
    ViewBag.Title = "Details";
}

<script>
    function BtnOnclick() {
        $.ajax({
            type: 'POST',
            url: '@Url.Content("~/Person/_Survey1")',
            data: {
                id: '@Model.Id'
            },
            success: function (data) {
                $('#divpopup').css("display", "block");
                $('#btnExpand').css("display", "none");
                $('#divpopup')[0].innerHTML = data;
            }
        });
    }
    function CollapseDiv() {
        $('#divpopup').css("display", "none");
        $('#btnExpand').css("display", "block");
    }




</script>
<h2>Details</h2>

<div>
    <h4>Person</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.FirstName)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.FirstName)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.LastName)
        </dt>


        <dd>
            @Html.DisplayFor(model => model.LastName)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.CellNumber)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.CellNumber)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.SecondaryPhoneNumber)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.SecondaryPhoneNumber)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Address)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Address)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.BirthDate)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.BirthDate)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Pesel)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Pesel)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Notes)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Notes)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.Status)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.Status.Name)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.PersonalDataProcessing)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.PersonalDataProcessing)
        </dd>
    </dl>
</div>
<!--BEGIN-->
<p>
    <input type="button" value="Expand" id="btnExpand"
           onclick="javascript:BtnOnclick();" />
</p>
<div id="divpopup" style="display:none">

</div>
<!--END-->

<p>@Html.ActionLink("Call Cell Phone", "Call", new { id = Model.Id, number = Model.CellNumber }, new { @class = "btn btn-default" })</p>
<p> @Html.ActionLink("Call Client's Secondary Number »", "Call", new { id = Model.Id, number = Model.SecondaryPhoneNumber }, new { @class = "btn btn-default" })</p>
<p>
    @Html.ActionLink("Edit", "Edit", new { id = Model.Id })
    @Html.ActionLink("Back to List", "Index")
</p>
4
  • There was an answer, what happened? Commented Aug 28, 2014 at 23:47
  • 1
    Always include the type attribute for buttons. Different browsers use different defaults, so it may be defaulting to submit. <button id='mybutton' type='button'>Click Me</button> Commented Aug 28, 2014 at 23:53
  • @StephenMuecke I fully updated the Original Post -> code and description. I added type='button' to the html. It prevented yellow screen of death, there are no runtime errors BUT nothing happens after click, there is no output on the console or anything. Commented Aug 29, 2014 at 0:06
  • 1
    Your also creating multiple buttons with the same id so its not going to work as you intend. I post an answer shortly. Commented Aug 29, 2014 at 0:08

3 Answers 3

3

Remove the script from the foreach loop and add a single script at the bottom of the page. In the loop, assign the values you want to pass to the post method as data attributes of the button so they can be accessed in the script. For example

@foreach (var survey in Model.Item2) {
  using (Html.BeginForm()) {
    ....
    <button class='mybutton' type='button' data-personid="@Model.Item.ID" data-surveyid="@Survey.ID">Click Me</button>

And the script

$('.mybutton').click(function() {
  var pid = $(this).data('personid');
  var sid = $(this).data('surveyid');
  var url = '@Url.Action("SubmitSurvey", "Person")';
  $.post(url, { personid: pid, surveyid: sid }, function(data) {
    alert('updated');
  });
});

Note: the post method should return JSON data indicating success or otherwise so you can test the result - for example return Json(true) or return Json(null), then in the script if(data) { alert('updated'); } else { alert('oops'); }

Sign up to request clarification or add additional context in comments.

5 Comments

I have tried exacly what you have posted. There were no errors but the java script function was never even invoked. I modified it little bit. Current code is in Original Post. I gave name to your function and added: onclick="javascript:SubmitClick()" to the button. This gives runtime error which says that definition of SubmitClick has not been found. I post in 2 minutes the screenshot in OP.
Oh my code after using your solution looked like this: wklej.org/id/1452605 nothing happenned.
_Survey1.html ** is PartialView** and it is invoked from Details.cshtml postem at the bottom of OP.
I posted answer. It works but I think it is done in old style. Could you refer please?
@Yoda, The script has to be placed at the bottom of the page or wrapped in $(document).ready! I don't see how your 'answer' works - your hard coding the values of personId and surveyId so they are always going to have the same value.
0

Don't put the script in the razor block, and as possible as put all script to the bottom of the page, in order to improve the page response well.

3 Comments

I'll be back working in 2 hours(asked question at 2am) but the reason I put it there was that there is local variable survey in foreach loop. That is why I put it there, I don't know how to pass it as parameter to JQuery method.
OK, let's consider that refactoring submit method in javascript, then pass the item.id and survey.id as parameter to the jQuery method. It's my way for you case, you could try it once if you have convenient time.
I don't know correct syntax yet. Could you present how to do it ?
0

I had to put script in the Details.cshtml which is master View to the _Survey1.cshtml(Partial View). Also putting this script in Details.csthml caused that server tried to execute it when I went to Details.cshtml(before even I clicked a button) causing runtime error:

$('.mybutton').click(function() {
  var pid = $(this).data('personid');
  var sid = $(this).data('surveyid');
  var url = '@UrlAction("SubmitSurvey", "Person")';
  $.post(url, { personid: pid, surveyid: sid }, function(data) {
    alert('updated');
  });
});

So I changed it to:

  function SubmitClick(pid, sid) {     
        var url = '@Url.Action("SubmitSurvey", "Person")';
        $.post(url, { personid: pid, surveyid: sid }, function (data) {
            alert('updated' + pid + " " + sid);
        });
    }

I had to add parameters because without them pid and sid were undefined, even though data-personid="@Model.Item1.Id" data-surveyid="@survey.Id" where defined in the button.

The button looks like:

  <button class='mybutton' type='button' onclick="javascript:SubmitClick(@Model.Item1.Id, @survey.Id.);" >Click Me</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.