问题
This is really weird, for some reason the Id of the ViewModel is being rendered as null inside the view. I debugged the application and checked that the view model is actually being mapped correctly (using AutoMapper) and everything is fine. But when I do @Model.Id, it is rendering as zero, and when I alert the value using jQuery I get "null". So what's going on?
<div id="commentBox">
@using (Html.BeginForm("Comment", "Item", new { itemId = Model.Id } ))
{
<span class="greenText">answer</span>
<span id="hiddenForId">@this.Hidden(x => x.Id).Id("idPlaceHolder")</span>
<span id="commentInputBox">@this.TextBox(x=>x.CommentText).Id("commentField")</span>
<span id="commentButton">@this.SubmitButton("").Id("commentSubmit").Class("okButton")</span>
}
</div>
<div style="clear:both"></div>
</div>
</div>
<script type="text/javascript">
$(function () {
alert($("idPlaceHolder").html());
$("#commentSubmit").click(function () {
var dataObj = { 'commentText': $("#commentField").val(), 'itemId': $("idPlaceHolder").html() }
$.ajax({
url: '/Item/Comment',
data: dataObj,
type: 'POST',
success: function (result) {
if (result.redirectTo != null && result.redirectTo != '') {
window.location.href = result.redirectTo;
} else {
alert(result.error);
}
}
});
return false;
});
});
</script>
P.S: on a side note, how do you tell the form that it doesn't need to post and that it has been taken care of? I just cannot remember it... It's definitely something other than return false;
回答1:
Partial answer: if you return false on a form's onsubmit event it will prevent the form from submitting.
回答2:
Right before you display the view - the model does have a value for ID, correct? In that case is this on a post? If so - if there are issues and you redisplay the form without a redirect MVC assumes an error it will use what was in the posted values to write back out- assuming you are creating a new record and the comment id was originally null. if this isnt during post/redisplay then this answer doesn't apply.
回答3:
Ok I've finally figured out what was going wrong:
$(function () {
alert($("#idPlaceHolder").val());
$("#commentSubmit").click(function () {
var dataObj = { 'commentText': $("#commentField").val(), 'itemId': $("#idPlaceHolder").val() }
I was using $("idPlaceHolder").html()
instead of $("#idPlaceHolder").val()
... syntax error!
来源:https://stackoverflow.com/questions/5720605/id-being-rendered-as-null-in-a-typed-razor-view