Search code examples
asp.net-mvcapiaction

ASP.NET MVC actions or APIs


I am new to ASP.NET development and I have a general question concerning APIs and actions.

I don't understand when to use APIs and when actions?

I know that APIs send data and this is necessary to display the application on various devices. And this is also required if another application wants to use the data.

But beside that? If for example I develop an application for computer webbrowser and no external application requests my data?

Can somebody explain please? Thank you in advance

Cini


Solution

  • Since you are asking the question from Asp.net MVC point of view, I am guessing you are talking about MVC Actions and Web API Actions. So here it is:

    • Use Asp.net MVC action which returns IActionresult type object which are usually the rendered output of a view (html/file contents). This is used to display data on the view/web pages without any extra rendering.

    For example a MVC Action may return data in this format:

    <div class="col-lg-12" id="list-table">
      <ul>
        <li>Data 1</li>
        <li>Data 2</li>
        <li>Data 3</li>
      </ul>                              
    </div>
    

    The above html can inserted in any web page or where you use Html without any extra manipulation.

    • Web API actions are mainly focused on data like (Json or Xml) which can be used to do various tasks including rendering data on the UI/Page or back-end calculation. The returned data is usually in raw format and you can render anything using that data.

    For example a Web API Action may return the followings:

    { 'list' : ['Data 1', 'Data 2', 'Data 3'] }
    

    Then to use the returned json data on a page (for example) you have to do the followings:

    for(var i = 0; i < data.list.length; ++i) {
      var li = document.createElement('li');
      li.appendChild(data.list[i]);
      ul.appendChild(li);                                 
    }
    
    document.getElementById('#list-table').append(ul);