JSON click event empty parameter

2019-08-04 09:48发布

问题:

Parameter string Temat is empty when I click button where is problem? It's look OK?

file.cshtml

    @using (Html.BeginForm())
    {
    <table class="edt" style="float: left; width: 600px; margin-top: 5px; background-color: white;">
    <tr>
                <td class="labelm">
                    @Html.LabelFor(m => m.Temat)<span id="Temat_2" class="a">*</span>
                </td>
                <td>
                    @Html.TextBoxFor(m => m.Temat,  new { id = "Temat" })
                </td>
    </tr>
    </table>
    <input type="button" value="save" onclick="Save();" />
    }

<script type="text/javascript">

    function Save() {
    var Temat = $('#Temat').val();

            $.ajax({
                url: '@Url.Action("DodajTematSave", "StronaGlowna")',
                dataType: "json",
                data: { Temat: Temat },
                type: "POST",
                async: false,
                error: function() {
                },
                success: function(data) {
                    if (data.Success) {
                        alert('success');
                    }

                }
            });
        }

</script>

JSON Method in Controller:

public JsonResult DodajTematSave(string Temat)
{
    var model = new StronaGlowna();
    if (!TryUpdateModel(model) || !ModelState.IsValid) // podładowanie yield 
    {
    }
    string chceSprobowac = Temat;
    return Json(new { Success = true});
}

回答1:

I suppose you want to retrieve the value of the textbox. If so, assign the id 'Temat' to the text box rather than then span and your code should work fine.

But if you are interested to retrieve the text of the span then use

var Temat = $('#Temat').text();

If you want to assign id to the textbox,

@Html.TextBoxFor(model => model.Password, new { id = "Temat" })