简体   繁体   English

Null value when posting data from a html form to a c# controller method using a JavaScript function

[英]Null value when posting data from a html form to a c# controller method using a JavaScript function

I am teaching myself how to program and I am having a hard time identifying an issue with my most recent experiment.我正在自学如何编程,但我很难确定我最近的实验存在的问题。 The following is within the context of an 'ASP.NET Web Application (.NetFramework) C#' and MVC architecture.以下是在“ASP.NET Web 应用程序 (.NetFramework) C#”和 MVC 架构的上下文中。

I am attempting to post data from a html form to a c# controller method using a JavaScript function. I am attempting to post data from a html form to a c# controller method using a JavaScript function.

The JavaScript function invokes the controller method; JavaScript function 调用 controller 方法; however, the string passed to the method always has a null value.但是,传递给该方法的字符串始终具有 null 值。 (I know that the new 'Organisation' instance is successfully created, as new instances appear with an ID in my database yet with a null name - as per my model). (我知道新的“组织”实例已成功创建,因为新实例在我的数据库中出现了一个 ID,但名称为 null - 根据我的模型)。

I have searched similar questions and tested contentType: application/json; charset=utf-8我搜索了类似的问题并测试了contentType: application/json; charset=utf-8 contentType: application/json; charset=utf-8 also; contentType: application/json; charset=utf-8也; however, my issue persists.但是,我的问题仍然存在。

The error reads: System.ArgumentNullException: 'Value cannot be null. Parameter name: s'错误显示: System.ArgumentNullException: 'Value cannot be null. Parameter name: s' System.ArgumentNullException: 'Value cannot be null. Parameter name: s' and occurs at var jsonDataParsed = JObject.Parse(jsonData); System.ArgumentNullException: 'Value cannot be null. Parameter name: s'并且出现在var jsonDataParsed = JObject.Parse(jsonData); in my c# controller method.在我的 c# controller 方法中。

I was hoping someone may be kind enough to help me:)我希望有人可以帮助我:)

The form:表格:

<form id="createOrganisationForm">

    <label for="organisationName">Organisation name</label>
    <input type="text" id="organisationName" />

    <input type="submit" onclick="createOrganisation()" value="submit" />

</form>

The Javascript function: Javascript function:

function createOrganisation() {

    var formData = {
        "OrganisationName": $("#organisationName").val()
    }

    $.ajax({
        url: '@Url.Action("CreateOrganisation", "Organisations")',
        type: "POST",
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        data: JSON.stringify(formData)
    })

}

The c# method in a controller: controller 中的 c# 方法:

[HttpPost]
public void CreateOrganisation(string jsonData)
{
    var jsonDataParsed = JObject.Parse(jsonData);
    var organisationName = jsonDataParsed["OrganisationName"].ToString();

    var organisation = new Organisation();
    organisation.Name = organisationName;
    db.Organisations.Add(organisation);
    db.SaveChanges();
}

The model: model:

public class Organisation
{
    public int OrganisationID { get; set; }
    public string Name { get; set; }
}

Try this:尝试这个:

function createOrganisation() {

    var formData = {
        "OrganisationName": $("#organisationName").val()
    }

    $.ajax({
        url: '@Url.Action("CreateOrganisation", "Organisations")',
        type: "POST",
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        dataType: 'json',
        data: {'formData': formData }
    })

}
 

Thank you everyone for your help.感谢大家的帮助。 Special thanks go to @Teemu for pointing me towards the final solution.特别感谢 go @Teemu 为我指出最终解决方案。

Below is a working solution;以下是一个可行的解决方案; I hope this may help others with future issues.我希望这可以帮助其他人解决未来的问题。

Key changes:主要变化:

  • name="organisationName" atrribute added to input name="organisationName"属性添加到输入
  • <input type="submit" edited to <button type="button" <input type="submit"编辑为<button type="button"
  • "parameter=" added to data: in ajax request "parameter="添加到data:在 ajax 请求中
  • ["OrganisationName"] edited to ["organisationName"] in C# method ["OrganisationName"] ["organisationName"]

Please refer to @Teemu advice in the question's comment section for the rationale behind these changes.请参阅问题评论部分中的@Teemu 建议,了解这些更改背后的基本原理。

The HTML form: HTML 形式:

<form id="createOrganisationForm">

    <label for="organisationName">Organisation name</label>
    <input type="text" id="organisationName" name="organisationName" />

    <button type="button" onclick="createOrganisation()">Submit</button>

</form>

The JavaScript function: JavaScript function:

function createOrganisation() {

    var formData = JSON.stringify({ organisationName: $("#organisationName").val()})

    $.ajax({
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        data: "jsonData=" + formData,
        url: '@Url.Action("CreateOrganisation", "Organisations")',
        type: "POST"
    })
}

Helpful note: the above script should be in the view file (not an external file) if you are using a razor @URL.Action有用的说明:如果您使用的是 razor @URL.Action,上述脚本应该在视图文件中(不是外部文件)

The c# controller method: c# controller 方法:

[HttpPost]
public void CreateOrganisation(string jsonData)
{
    var jsonDataParsed = JObject.Parse(jsonData);
    var organisationName = jsonDataParsed["organisationName"].ToString();

    var organisation = new Organisation();
    organisation.Name = organisationName;
    db.Organisations.Add(organisation);
    db.SaveChanges();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM