Umbraco - how to set the value of a property using

2020-07-20 03:48发布

问题:

I'm trying to create a very simple polling form and I thought of having a go at it using razor instead of using an external control.

I've created a form that lists one question and a list of answers and when we press submit we go to the page that calls the razor script that handles the results.

What I want to do is loop through all the answers and increment their counter by one. There is a numeric property called "Counter" on each Answer object.

However that keeps failing. If I do:

var objAnswer = @Model.NodeById(Int32.Parse(submittedAnswer));
objAnswer.getProperty("Counter").Value++;

or similar ways, they all fail. What is weird is that objAnswer.getProperty("Counter") does contain a number, but when I try to set it I get this error:

   umbraco.MacroEngines.DynamicNull' does not contain a definition for 'Value'

I get I've also tried with

Document post = new Document(objAnswer.Id);
post.Publish(user);

but that fails as well.

Is there an easy way of achieving this?


The answer is this!!

      Document doc = new Document(objAnswer.Id);
      doc.getProperty("counter").Value = 34;
      umbraco.BusinessLogic.User author = umbraco.BusinessLogic.User.GetUser(0); 
      doc.Publish(author);
      umbraco.library.UpdateDocumentCache(doc.Id);

Not that the property needs to be lower case.

回答1:

Model.NodeById() returns a DynamicNode object, the properties of which are read only. You'll want to go the Document route for sure, especially since both Node and DynamicNode both get their data from the XML cache, whereas Document manipulates the database.