指數 - 查看如何在MVC中單擊按鈕時將模型從視圖傳遞到控制器?
@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成爲JavaScript的不工作
<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>
控制器
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.
已應用HttpPost屬性到控制器的動作?我問你的JavaScript做了一個帖子,沒有屬性的動作的默認行爲是隻接受GET請求。 –
有多個錯誤。如果警報沒有顯示,請檢查您的瀏覽器控制檯是否有錯誤(您是否加載了jquery?)。 e.preventDefault();'什麼都不做,因爲沒有'e'(它需要是'$(「#btnSend」)。click(function(e){'如果你想取消提交事件''' var model = @ Html.Raw(Json.Encode(Model))''是原始模型(不是已經編輯過的),所以你的腳本毫無意義 - 你只需要發回控制器發送的內容 –
@StephenMuecke我已經刪除'e.preventDefailt();'我發佈了實際編輯過的內容,我在瀏覽器控制檯上檢查錯誤'localhost /:69 Uncaught ReferenceError:$ is not defined'。我該如何解決這個問題? – User123