Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

javascript - How to pass model from view to controller when click button in MVC?

Index - View

@model SendAFaxWeb.Models.Send
//view start here
<body>
    <div>
        <h2>Test Upload File</h2>
        <form action="@Url.Action("Index", "Home")" id="form" method="post" enctype="multipart/form-data">
            @Html.AntiForgeryToken()
            <div class="form-group">
                <label>Fax Number:</label>
                @Html.TextBoxFor(m => m.Recipients[0].Number)
             </div>

            <div class="form-group">
                <label>Select File:</label>
                <input type="file" name="files" id="file" multiple="multiple" onchange="this.form.submit();" />
            </div>

            <div>
              @if (Model != null)
                 {
                   foreach (var item in Model.Documents)
                    {
                       <li>FileName: @item.Name</li>
                    }
                  }
             </div>
    </form>

    <input type="submit" name="send" value="Send" id="btnSend" />

    </div>
</body>

Javascript- the javascript doesnt work

<script type="text/javascript">
    $(document).ready(function () {
     $("#btnSend").click(function () {
        alert("button click");
        e.preventDefault();

        var model = @Html.Raw(Json.Encode(Model))
        $.ajax({
            type: 'post',
            url: '@Url.Action("Send", "Home")',
            data: JSON.stringify({ contact: model }),
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            success: function (data) {
                alert(data);
            }
        });
        });
    });

</script>

Controller

public ActionResult Send(Send contact)
{
    //some code here
}

I tried to pass model by using javascript to the controller, but its not working. The alert in javascript also not popup. Can any one tell me what wrong with the code.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do it using the below code

@model PK.LifeStyles.Web.Models.Reimbursement //model declaration on top

<button type="button" onclick="location.href='@Url.Action("ActionName", "ControllerName",Model)'">

Your code behind should look something like this

    public ActionResult Save(Reimbursement data)
    {
      // your  code
    }
   //just some random class
   public class Reimbursement{
         public string Destination { get; set; }
   }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...