I have a simple question: How can I send form fields via AJAX after a user fills them out without reloading the page? I am using @Html.EditorForModel()
to generate the fields for my model.
I've researched different approaches, but it seems like there isn't a standard method to accomplish this. I don't have an object on the client-side that represents the model. I did find one library called JSModel
, but unfortunately, it doesn't seem to be working properly (link). My current code looks like this:
@model Student
<script src="@Url.Content("~/scripts/jquery-1.12.2.min.js")" type="text/javascript" async="async"></script>
<script src="@Url.Content("~/scripts/Requester.js")" type="text/javascript" async="async"></script>
<script src="@Url.Content("~/scripts/jsmodel.js")" type="text/javascript"></script>
<script type="text/javascript">
var requester = new Requester(@Html.Raw(Json.Encode(new Student())));
function SendSignupRequest() {
requester.SendSignupRequest();
}
</script>
<h2>Student</h2>
<div>
@Html.EditorForModel()
</div>
<input type="button" value="Send" onclick="SendSignupRequest()"/>
Requester.js:
function Requester(rawModel) {
this.modelObj = new JSModel(rawModel);
this.SendSignupRequest = function() {
var model = modelObj.refresh();
var val = model.prop("Name");
alert(val);
}
}
Is there a straightforward way to serialize a model object in JSON and send it to the server, without having to manually construct an object using numerous document.getElementById
calls?