I want to update model value in JavaScript as below but it is not working.
function updatePostID(val) { @Model.addcomment.PostID = val; }
in Razor view as shown below
foreach(var post in Model.Post) { <br/> <b>Posted by :</b> @post.Username <br/> <span>@post.Content</span> <br/> if(Model.loginuser == Model.username) { @Html.TextAreaFor(model => model.addcomment.Content) <button type="submit" onclick="updatePostID('@post.PostID');">Add Comment </button> } }
Can anyone tell me how to assign model value in JavaScript?
When you click the submit button, the HttpPost action method above will be executed and the value of model. FavoriteColor will be what you select in the dropdownlist. After that you can use that value to update your database. and you can get the person id in model.
Right-click in the Store Index action method and select Add View as before, select Genre as the Model class, and press the Add button. This tells the Razor view engine that it will be working with a model object that can hold several Genre objects.
To declare the model type, use the @model directive. Show activity on this post. Note the lowercase @model since uppercase prints the value of the Model property.
Solution 1. You can't. Razor is a . NET assembly and doesn't run on JavaScript or in a browser.
This should work
function updatePostID(val) { document.getElementById('PostID').value = val; //and probably call document.forms[0].submit(); }
Then have a hidden field or other control for the PostID
@Html.Hidden("PostID", Model.addcomment.PostID) //OR @Html.HiddenFor(model => model.addcomment.PostID)
The model (@Model
) only exists while the page is being constructed. Once the page is rendered in the browser, all that exists is HTML, JavaScript and CSS.
What you will want to do is put the PostID in a hidden field. As the PostID value is fixed, there actually is no need for JavaScript. A simple @HtmlHiddenFor
will suffice.
However, you will want to change your foreach loop to a for loop. The final solution will look something like this:
for (int i = 0 ; i < Model.Post; i++) { <br/> <b>Posted by :</b> @Model.Post[i].Username <br/> <span>@Model.Post[i].Content</span> <br/> if(Model.loginuser == Model.username) { @Html.HiddenFor(model => model.Post[i].PostID) @Html.TextAreaFor(model => model.addcomment.Content) <button type="submit">Add Comment</button> } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With