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
285 views
in Technique[技术] by (71.8m points)

c# - ASP.NET MVC: Hidden field value does not get rendered using HtmlHelper.Hidden

Something pretty weird is happening with my app:

I have the following property in my ViewModel:

public int? StakeholderId { get; set; }

It gets rendered in a partial view as follows:

<%= Html.Hidden("StakeholderId", Model.StakeholderId) %>

The form is submitted, and the relevant controller action generates an id and updates the model, before returning the same view with the updated model

The problem I'm experiencing is that the hidden field does not have anything in its "value" attribute rendered the second time even though StakeholderId now has a value.

If I just output the value on its own, it shows up on the page, so I've got it to render the value by doing this:

<input type="hidden" id="StakeholderId" name="stakeholderId" value="<%: Model.StakeholderId %>" />

But it's pretty strange that the helper doesn't pick up the updated value?

(I'm using jQuery to submit forms and render the action results into divs, but I've checked and the html I get back is already wrong before jQuery does anything with it, so I don't think that has much to do with anything)

UPDATE

I've since discovered that I can also clear the relevant ModelState key before my controller action returns the partial view.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The helper will first look for POSTed values and use them. As you are posting the form it will pick up the old value of the ID. Your workaround is correct.


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

...