Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update a model value in JavaScript in a Razor view?

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?

like image 625
michaeld Avatar asked Apr 23 '13 16:04

michaeld


People also ask

How do I update view model?

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.

How do you use a model in razor view?

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.

How do you specify a model in view?

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.

Can I use Javascript in razor?

Solution 1. You can't. Razor is a . NET assembly and doesn't run on JavaScript or in a browser.


2 Answers

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) 
like image 142
codingbiz Avatar answered Sep 21 '22 02:09

codingbiz


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>     } } 
like image 20
Jason Berkan Avatar answered Sep 22 '22 02:09

Jason Berkan