[MVC][Razor] Exchange data between editortemplates

34 views Asked by At

A bit new to using EditorTemplates and stumped on the following:

I have a multi layered (view)model, simplified like this:

public class MyModel()
{
   public MyFirstSubModel MyFirstSubModel { get; set; }
   public MySecondSubModel MySecondSubModel { get; set; }
}

For each submodel I made an EditorTemplate, like so:

@model MyFirstSubModel

<div>
@Html.TextBoxFor(m => m.SomeThing)
</div>

and

@model MySecondSubModel

<div>
@Html.TextBoxFor(m => m.AnotherThing)
</div>

These two are shown as different tabs on the main View, like so:

<div class="tab-content">
   <div class="tab-pane fade">
      @Html.EditorFor(m => m.MyFirstSubModel)
   </div>
   <div class="tab-pane fade">
      @Html.EditorFor(m => m.MySecondSubModel)
   </div>
</div>

The controller is nothing more than a conduit making calls to service library which makes calls to a WebAPI in which another Controller talks to the real model to fetch and save data. That model is an Entity Framework one.

All works pretty well, until the specs changed and I was asked to change the value of MySecondSubModel.AnotherThing when the user changes MyFirstSubModel.SomeThing. Ideally without having to reload everything which would defeat the purpose of having templates I think.

What I have tried to do was write an Ajax call in the MyFirstSubModel EditorTemplate to get the value I would need to put in MySecondSubModel EditorTemplate. That part is coming along nicely, but having the value in the first EditorTemplate I have no idea how to get it into the second one.

Bonus question: how to retrieve a value from lets say a third EditorTemplate to use as an additional parameter for the Ajax call in the first EditorTemplate to retrieve the value for the second EditorTemplate?

I hope I have made any sense in my question, maybe I am going about this the wrong way, I am still learning. Hopefully can get some usefull pointers. TIA!

1

There are 1 answers

1
Poutrathor On

thanks for the effort you put in the question.

I am not knowledgeable in razor.

However, if you can use ajax (thus javascript), you can create a JS function that your ajax will call when successful. This function will update the value in the second template.

Using any web framework should not make you forget that in the end, there always is an HTML web page that is rendered by a browser with included js scripts.

document.getElementById("content").innerHTML = "ajax value answer";

Hope it helps you ordering your though process. I +1 your question, someone better might drop by and help you more !