如果“可选参数”概念不起作用怎么办?

时间:2018-07-21 07:25:52

标签: javascript c# asp.net-mvc

我有一个JS函数,该函数根据所选的单选按钮从文本框中获取一个值。

示例:如果选择了RadioButton ,则从 TextBox A 中获取值;否则,如果选择RadioButton ,则取自文本框B 。我认为以下脚本

$('#btnVolunteerSaveBtn').on('click', function() { // on click of save button
  if (document.getElementById('RadioNo').checked) { //ID of radio button NO
    var checking = $('#Donation').val(); //ID of textbox from where the value is to be taken if RadioButton No is selected
    if (checking == "") {
      //if nothing is entered, stop from saving in DB
    } else {
      x = $('#Donation').val(); //ID of textbox from where the value is to be taken if RadioButton No is selected
      $.ajax({
        url: '@Url.Action("DonationValue","VolunteerInfo")',
        data: {
          name: x
        },
        type: "POST"
      });
    }
  } else {
    x = $('#GetNames').val(); //ID of textbox from where the value is to be taken if RadioButton Yes is selected
    $.ajax({
      url: '@Url.Action("DonationValue","VolunteerInfo")',
      data: {
        name: x
      },
      type: "POST"
    });
  }
});

到这里似乎一切正常。现在进入控制器,我有一个函数DonationValue

我的问题:

  1. 如何传递上面的name参数?
  2. 如果在ID为#Donation的文本框中未填充任何内容,如何停止 将表单保存到数据库中?

我的尝试:

我尝试做

public string DonationValue(string name = null)
{
    return name; //Trying to pass this value above
}

这没有帮助。它解决了该错误,但传递的值始终为null。我还尝试了其他几件事,但没有帮助。

已编辑:

[HttpPost]
public ActionResult AddVolunteer(VolunteerInfo viewModel)
{
    if (!ModelState.IsValid)
    {
        return View("AddVolunteer", viewModel);
    }

    var volunteer = new VolunteerInfo()
    {
        Name = viewModel.Name,
        BirthdayDateTime = viewModel.BirthdayDateTime,
        Address = viewModel.Address,
        PhoneNumber = viewModel.PhoneNumber,
        EmailAddress = viewModel.EmailAddress,
        OccasionsID = viewModel.OccasionsID,
        DonationForWhom = _DonationValue
    };

    if (!string.IsNullOrEmpty(volunteer.DonationForWhom))
    {
        _context.VolunteerInfos.Add(volunteer);
        _context.SaveChanges();
        return RedirectToAction("Index", "Home");
    }

    return //something to save state so that user doesnt have to enter all the values again
}

[HttpPost]
public void DonationValue(string name)
{
    _DonationValue = name;
}

2 个答案:

答案 0 :(得分:1)

@Daisy Shipton。 这是更好的解决方案吗?

<script>
        $(function() {
            $('#btnVolunteerSaveBtn').on('click', function() { // on click of save button
                debugger;
                if (document.getElementById('RadioNo').checked) { //ID of radio button NO
                    var checking = $('#Donation').val(); //ID of textbox from where the value is to be taken if RadioButton No is selected
                    if (checking == "") {
                        //if nothing is entered, stop from saving in DB
                    }
                    else {
                        var x = $('#Donation').val(); //ID of textbox from where the value is to be taken if RadioButton No is selected
                        var jsonObject = {
                            "textValue": x,
                            "isRadioSelected": "true" // show the radio is selected
                        };

                        $.ajax({
                            url: '@Url.Action("AddVolunteer", "VolunteerInfo")',
                            data: JSON.stringify(jsonObject),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            type: "POST",
                            error: function (response) {
                                alert(response.responseText);
                            },
                            success: function (response) {
                                alert(response);
                            }
                        });
                    }
                }
                else {
                    var jsonObject2 = {
                        "textValue": $('#GetNames').val(),
                        "isRadioSelected": "false" // show the radio is not selected
                    };

                    $.ajax({
                        url: '@Url.Action("AddVolunteer", "VolunteerInfo")',
                        data: JSON.stringify(jsonObject2),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        type: "POST",
                        error: function (response) {
                            alert(response.responseText);
                        },
                        success: function (response) {
                            alert(response);
                        }
                    });
                }

            });
        })
    </script>

在我的控制器中:

[HttpPost]
    public ActionResult AddVolunteer(VolunteerInfo volunteerInfo)
    {
        if (volunteerInfo.isRadioSelected)
        {
            //something
        }
        else
        {
           //something
        return View();
    }

答案 1 :(得分:0)

1)客户端调用名称为paramter的DonationValue post方法

例如name="abc"

[HttpPost]
public string DonationValue(string name = null)  // name = "abc"
    {
        return name; //Trying to pass this value above
    }

此返回值存储在客户端,例如变量retunedDonationValue

如果您不传递任何名称参数,则上述post方法会返回空字符串,然后只需设置retunedDonationValue = ''

2)现在,您必须在retunedDonationValue上方传递给已发布的json对象中的post方法,例如

var jsonObject = 
                {
                    "Name" = "YourName",
                    "BirthdayDateTime" = "YourBirthdayDateTime",
                    "Address" = "YourAddress",
                    "PhoneNumber" = "YourPhoneNumber",
                    "EmailAddress" = "YourEmailAddress",
                    "OccasionsID" = "YourOccasionsID",
                    "DonationForWhom" = retunedDonationValue  //Note here
                }

3)并将此帖子数据传递到对AddVolunteer的http调用

                    $.ajax({
                        url: '@Url.Action("AddVolunteer", "VolunteerInfo")',
                        data: JSON.stringify(jsonObject),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        type: "POST",
                        error: function (response) {
                            alert(response.responseText);
                        },
                        success: function (response) {
                            alert(response);
                        }
                    });

4)您的动作方法看起来像

[HttpPost]
    public ActionResult AddVolunteer(VolunteerInfo viewModel)
    {
        if (!ModelState.IsValid)
        {
            return View("AddVolunteer", viewModel);
        }

        var volunteer = new VolunteerInfo()
        {
            Name = viewModel.Name,
            BirthdayDateTime = viewModel.BirthdayDateTime,
            Address = viewModel.Address,
            PhoneNumber = viewModel.PhoneNumber,
            EmailAddress = viewModel.EmailAddress,
            OccasionsID = viewModel.OccasionsID,
            DonationForWhom = viewModel.DonationForWhom
        };

        if (!string.IsNullOrEmpty(volunteer.DonationForWhom))
        {
            _context.VolunteerInfos.Add(volunteer);
            _context.SaveChanges();
        }

        return View(viewModel);

    }