Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
4.8 kB
4
Indexable
Never
Backend
 
IRepository.cs
public Task<string> GetDescription(string title);

Repository.cs
public async Task<string> GetDescription(string title){
       
           var blogDescrition = await _context.Blogs.Where(x=>x.BlogTitle==title)
           .Select(x=>x.BlogDescription).FirstOrDefaultAsync();
            return blogDescrition;
           
      

   }


BlogControoler.cs
[HttpGet("GetDescription")]
       public async Task<ActionResult<string>> GetDescription([FromQuery]string title){
           var b=await _blogRepository.GetDescription(title);
           if(b==null){
               return NotFound("Errorrrr");
           }else{
               return Ok(b);
           }
       }



Frontend--

SearchForAdmin.jsx
import React, { useState, useEffect } from 'react';
import { useFormik } from 'formik';
import { Link, useNavigate } from 'react-router-dom';
import axios from 'axios';
import './searchh.css';
 
const Search = () => {
  const formik = useFormik({
    initialValues: {
      searchQuery: '',
    },
    onSubmit: (values) => {
      fetchTitles(values.searchQuery);
    },
  });
 
  const [blogTitles, setBlogTitles] = useState([]);
  const [displayedBlogTitles, setDisplayedBlogTitles] = useState([]);
  const navigate = useNavigate(); // useNavigate hook for navigation
 
  useEffect(() => {
    fetchBlogTitles();
  }, []);
 
  const fetchBlogTitles = async () => {
    try {
const response = await axios.get('http://localhost:5221/api/Blog/GetTitles');
      const data = response.data;
      setBlogTitles(data);
      setDisplayedBlogTitles(data);
    } catch (error) {
      console.error('Error fetching blog titles:', error);
    }
  };
 
  const fetchTitles = async (searchQuery) => {
    try {
const response = await axios.get(`http://localhost:5221/api/Blog/SearchByTitle?title=${searchQuery}`);
      const data = response.data;
 
      if (searchQuery) {
        setDisplayedBlogTitles(data);
        console.log('Searched:', data);
      } else {
        setDisplayedBlogTitles(blogTitles);
        console.log('Not able to search');
      }
    } catch (error) {
      console.error('Error in searching:', error);
    }
  };
 
  const handleBlogTitleClick = (title) => {
    navigate(`/blog/${encodeURIComponent(title)}`);
  };
 
  return (
    <div className="search-container">
       <form onSubmit={formik.handleSubmit}>
        <div className="search-bar-container">
          <input
            type="text"
            id="searchQuery"
            name="searchQuery"
            placeholder="Search..."
            onChange={formik.handleChange}
            value={formik.values.searchQuery}
          />
          <div className="button-container">
            <button type="submit">Search</button>
          </div>
        </div>
      </form>
 
      <div className="blog-titles-container">
        <h2>{formik.values.searchQuery ? 'Search Results' : 'All Blogs'}</h2>
        <div className="blog-titles">
          {displayedBlogTitles.map((title, index) => (
            <div key={index} className="blog-title" onClick={() => handleBlogTitleClick(title)}>
              {title}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};
 
export default Search;


BlogDetailPages.jsx
import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import axios from 'axios';
import './searchh.css';
 
const BlogDetailsPage = () => {
  const { title } = useParams();
  const [blogDetails, setBlogDetails] = useState({ title: '', description: '' });
 
  useEffect(() => {
    fetchBlogDetails(title);
    console.log("useeffect working");
  }, [title]);
 
  const fetchBlogDetails = async (blogTitle) => {
    try {
  const response = await axios.get(`http://localhost:5221/api/Blog/GetDescription?title=${encodeURIComponent(blogTitle)}`);
      const data = response.data;
      setBlogDetails(data);
      console.log("api response",data);
    } catch (error) {
      console.error('Error fetching blog details:', error);
      console.error('Response:', error.response); // Log the response for more details
    }
  };
 
  return (
    <div>
      <h2>Title : {blogDetails.title}</h2>
      <p>Description : {blogDetails.description}</p>
    </div>
  );
};
 
export default BlogDetailsPage;

Main.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Search from './SearchForAdmin';
import BlogDetailsPage from './BlogDetailsPage';
import './searchh.css';
 
ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <Router>
      <Routes>
        <Route path="/" element={<Search />} />
        <Route path="/blog/:title" element={<BlogDetailsPage />} />
      </Routes>
    </Router>
  </React.StrictMode>,
);


Leave a Comment