You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Admin端获取Vacancy数据并在Client端展示(含空状态及代码问题)

It looks like the core issue here is that your Admin endpoint is returning a view (HTML) instead of raw data (JSON), which is why your Client can't properly parse the vacancy details (leading to null values for properties like vacancytitle). Let's fix this end-to-end, from the Admin API to the Client view:

Step 1: Fix the Admin API to Return JSON Data

Your current DisplayVacancyData method returns a view, which is meant for rendering a web page—not for data consumption by another app. Let's create a dedicated API endpoint in your Admin project that returns the vacancy list as JSON:

// In your Admin's VacancyController (or similar)
[HttpGet("api/vacancies")]
public IActionResult GetVacancies()
{
    // Fetch all vacancies from tbl_vacancy using Entity Framework
    var vacancies = _context.tbl_vacancy.ToList();
    
    // Return as JSON (OkObjectResult automatically serializes to JSON)
    return Ok(vacancies);
}

Make sure _context is your injected DbContext instance pointing to the database with tbl_vacancy.

Step 2: Update the Client's Career Controller Method

Next, adjust your Client's HomeController.Career method to correctly call this new API endpoint and deserialize the JSON response into your Vacancy objects. We'll use IHttpClientFactory (best practice for HttpClient usage in ASP.NET Core):

First, register HttpClient in your Client's Program.cs (or Startup.cs if using older .NET):

builder.Services.AddHttpClient();

Then, modify the HomeController:

private readonly HttpClient _httpClient;

// Inject HttpClient via constructor
public HomeController(HttpClient httpClient)
{
    _httpClient = httpClient;
    // Set the base URL of your Admin API (update this to your actual Admin domain)
    _httpClient.BaseAddress = new Uri("https://your-admin-api-domain.com/");
}

public async Task<IActionResult> Career()
{
    List<Vacancy> vacancies = new();
    
    try
    {
        // Call the Admin API endpoint we created
        var response = await _httpClient.GetAsync("api/vacancies");
        
        if (response.IsSuccessStatusCode)
        {
            // Deserialize the JSON response into a list of Vacancy objects
            vacancies = await response.Content.ReadFromJsonAsync<List<Vacancy>>() ?? new();
        }
    }
    catch (Exception ex)
    {
        // Log the error (use a logging framework like Serilog or built-in ILogger)
        // For now, we'll just leave vacancies as an empty list
    }
    
    // Pass the vacancy list to the view using a strongly-typed model (better than ViewBag)
    return View(vacancies);
}

Step 3: Ensure Your Client's Vacancy Class Matches the API Response

Double-check that your Client's Vacancy class has property names that match the JSON returned by the Admin API. For example, if your tbl_vacancy has columns vacancytitle, description, location, your class should look like this (adjust to match your actual schema):

public class Vacancy
{
    public int Id { get; set; }
    public string Vacancytitle { get; set; } // Match the column name (case-sensitive if using default serialization)
    public string Description { get; set; }
    public string Location { get; set; }
    // Add other properties from tbl_vacancy as needed
}

If the Admin uses camelCase for JSON (common in ASP.NET Core), you can use [JsonPropertyName] attributes to map correctly:

using System.Text.Json.Serialization;

public class Vacancy
{
    public int Id { get; set; }
    [JsonPropertyName("vacancytitle")]
    public string VacancyTitle { get; set; } // Your Client can use PascalCase, map to camelCase JSON
    // ... other properties
}

Step 4: Update the Career View to Display Data & Handle Empty State

Now, modify your Career.cshtml to use the strongly-typed model and show either the vacancy list or the "暂无职位空缺" message:

@model List<Vacancy>

@{
    ViewData["Title"] = "Career";
}

<h1>Career Opportunities</h1>

@if (Model.Any())
{
    <div class="row">
        @foreach (var vacancy in Model)
        {
            <div class="col-md-4 mb-4">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">@vacancy.Vacancytitle</h5>
                        <p class="card-text">@vacancy.Description</p>
                        <p class="card-text"><small class="text-muted">Location: @vacancy.Location</small></p>
                        <!-- Add more details or a "Apply" button if needed -->
                    </div>
                </div>
            </div>
        }
    </div>
}
else
{
    <div class="alert alert-info mt-4">
        暂无职位空缺
    </div>
}

Why Your Original Approach Failed

  • Admin Returned HTML Instead of JSON: Your DisplayVacancyData method returned a view (HTML), so when your Client called it, it was trying to parse HTML into Vacancy objects—hence all properties were null.
  • Incorrect Data Passing: Using ViewBag can work, but if the deserialization failed, ViewBag would hold invalid data. Strongly-typed models are more reliable and easier to debug.

内容的提问来源于stack exchange,提问作者Aayushi Babariya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 11:42:31