So in my view, I just want to be able to read the values provided by the Model.
@{
var bgPath = "../Files/somedir/" + Model.FilePath;
}
So I can just dump it into a string to render an image to the DOM:
<img id="bg-image" class="background-image" src="@bgPath" draggable ="false" alt="" />
Now, this works perfectly fine. My view renders properly. My problem is that when the form is submitted, it throws up an error that Model.FilePath is null.
The code is already OUTSIDE the main (and only) form field in the view.
I do not want to bind this data, I’m ONLY using it to give values to js. I have many other fields that seemed like they were going to work and there’s not really the option of changing it without a load of rewrite.
So my question is, how to get read-only model values?
you need to keep that in a hidden field in your form so that MVC model binding will make it available when submitting form.
But remember that, the hidden value field can be changed using browser extensions (like firebug) before posting. So If you are not updating the filepath by reading a new value from the user, do either one of this
1) Update only the relevant fields. Have an Update method which updates only the relevant fields for the model.
2) If updating all fields, Read from the domain object first and the update