3

I have the following component:

class MyComponent extends React.Component {
    render() {
        return ( <div>  
            <label>{this.props.myData.Count()}</label>
        </div>
    );
}

The idea being that the control displays a count of the data being passed in; here's what's currently in the Asp.Net View:

<div>
    <MyComponent myData={@Model.MyData} />            
</div>

I can see in the inspector that a value of myData has been passed to MyComponent, I also know that there is data inside of the MyData collection, but it isn't displaying anything.

I've also tried this:

@Html.React("MyComponent", new { myData = Model.MyData });

<div id="content">
    <MyComponent />
</div>

But that doesn't render at all.

I can get the control to render by using the following format:

<div id="content">
</div>
<script src="@Url.Content("~/js/component.jsx")"></script>

But this doesn't allow me to pass data in.

Being quite new to React, I assume that I need to somehow tell the component to expect an object, or something similar. Could someone point me in the right direction, please?

3
  • do you have an existing asp application that you're trying to sprinkle some react into? Commented Aug 29, 2018 at 15:12
  • Yes - sorry, I should have made that clear. This isn't a new application, it's an existing Asp.Net Core 2 application, and I'm trying to use React for a specific feature. Commented Aug 30, 2018 at 6:59
  • Hi User, did you end up connecting the dots of react and .net? Commented Mar 11, 2019 at 18:46

1 Answer 1

2

Old question, but I stumbled on this while researching the same problem. I had some luck passing my data over as a global javascript variable from the vbhtml/cshtml file.

My abridged vbhtml:

@Using (Html.BeginForm())
    @<div id="createdropdown” ></div>
    @<script src="~/scripts/bundle.js"></script>
    @<script>
        var gTypes = @Html.Raw(Json.Encode(Model));
     </script>
End Using

My data converted to a json array (note that I structured the data to be in the format accepted by the react-select component's options):

"[{ value: 'chocolate', label:'Chocolate' },{ value: 'strawberry', label: 'Strawberry' },{ value: 'vanilla', label: 'Vanilla' }]"

my jsx:

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import Select from 'react-select'

class CreateForm extends React.Component {
        render() {
            return (<Select options={this.props.types} placeholder="Type" />);
       }
}

ReactDOM.render(<CreateForm types={gTypes} / >, document.getElementById('createdropdown'));

Hope that helps :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.