하나의 뷰에서 뷰 생성과 인덱스 뷰 코드를 혼합했습니다. 그렇다면 asp.net MVC4의 해당 뷰로 데이터베이스에서 데이터를 검색하는 방법은 무엇입니까?

Ayman

하나의 뷰에서 두 뷰를 병합했습니다 (하나는 생성하고 다른 하나는 표시). 따라서 새 뷰는 동시에 데이터를 추가하고 검색 할 수 있습니다. 그러나 아무것도 검색하지 않고 데이터베이스에 새 행을 만들 수만있었습니다. 데이터베이스에는 4 개의 행이 있습니다.

여기에 내 새 뷰 (색인)가 있습니다. foreach가 작동하는지 확인하기 위해 h1> Works / h1>을 추가했습니다.

Index.cshtml

    @model ReMvc.ViewModel.MovieViewModel
    @using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Movie</legend>
        <div class="editor-label">
            @Html.LabelFor(movie => movie.Movie.Title)
        </div>
        <div class="editor-field">
            @Html.EditorFor(movie => movie.Movie.Title)
            @Html.ValidationMessageFor(movie => movie.Movie.Title)
        </div>

        <div class="editor-label">
            @Html.LabelFor(movie => movie.Movie.ReleaseDate)
        </div>
        <div class="editor-field">
            @Html.EditorFor(movie => movie.Movie.ReleaseDate)
            @Html.ValidationMessageFor(movie => movie.Movie.ReleaseDate)
        </div>
        <div class="editor-label">
            @Html.LabelFor(movie => movie.Movie.Genre)
        </div>
        <div class="editor-field">
            @Html.EditorFor(movie => movie.Movie.Genre)
            @Html.ValidationMessageFor(movie => movie.Movie.Genre)
        </div>

        <div class="editor-label">
            @Html.LabelFor(movie => movie.Movie.Price)
        </div>
        <div class="editor-field">
            @Html.EditorFor(movie => movie.Movie.Price)
            @Html.ValidationMessageFor(movie => movie.Movie.Price)
        </div>
        <p>
            <input type="submit" value="Create" />

        </p>
    </fieldset>
       foreach (var item in Model.MovieCollection)
        {
            <tr>
                <h1>Works</h1>
                <td>
                    @Html.Display(item.Title)
                </td>
                <td>
                    @Html.Display(item.ReleaseDate.ToString())
                </td>
                <td>
                    @Html.Display(item.Genre)
                </td>
                <td>
                    @Html.Display(item.Price.ToString())
                </td>
            </tr>
    }

    }
    <p>
        </p>
    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }

위 코드에서 foreach가 MovieCollection에서 색인 페이지로 데이터를 검색하지 않는 내 문제. 내 모델 (영화)은 다음과 같습니다.

    using System;
    using System.Data.Entity;

    namespace ReMvc.Models
    {
        public class Movie
        {
            public int ID { get; set; }
            public string Title { get; set; }
            public DateTime ReleaseDate { get; set; }
            public string Genre { get; set; }
            public decimal Price { get; set; }
        }

        public class MovieDbContext : DbContext
        {
            public DbSet<Movie> Movies { get; set; }
        }
    }

그리고 여기에 문제를 해결하는 새로운 유형이 있습니다.

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;

 namespace ReMvc.ViewModel
 {
    public class MovieViewModel
    {
        public ReMvc.Models.Movie  Movie  { get; set; }
        public IEnumerable<ReMvc.Models.Movie>  MovieCollection { get; set;      }
    }
}

내 컨트롤러는 다음과 같습니다.

  using System;
  using System.Collections.Generic;
  using System.Data;
  using System.Data.Entity;
  using System.Linq;
  using System.Web;
  using System.Web.Mvc;
  using ReMvc.Models;
  using ReMvc.ViewModel;

 namespace ReMvc.Controllers
 {
    public class MoviesController : Controller
    {
        private MovieDbContext db = new MovieDbContext();
        //
        // GET: /Movies/

        public ActionResult Index()
        {

            var model = new MovieViewModel()
            { MovieCollection = db.Movies.ToList(), };
            return View(model);
        }

        //
        // POST: /Movies/Index

        [HttpPost]
        public ActionResult Index(Movie movie)
        {
            if (ModelState.IsValid)
            {
                db.Movies.Add(movie);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            var model = new MovieViewModel()
            {
                Movie = movie,
            };
            return View(movie);
        }

    }
아크람 알샤 미리

1. 엔터티 폴더의 모델에서 foreach와 함께 사용할 열거 가능한 행 목록을 추가합니다.

public partial class UserProfile
    {
        public int UserId { get; set; }
        public string UserName { get; set; }
        public string PostContent { get; set; }
        public IEnumerable<workingOnAddPost.Entity.UserProfile> UserProfilesCollection { get; set; }

2. httpPost 및 httpGet 요청을 처리하도록 홈 컨트롤러를 편집합니다.

public class HomeController : Controller
{
    private AddingPostEntities db = new AddingPostEntities();

    [HttpGet]
    public ActionResult Index()
    {
        ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

        //return View( db.UserProfiles.ToList());


        var model = new UserProfile() 
        {
            UserProfilesCollection = db.UserProfiles.ToList(), 
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(UserProfile userprofile)
    {
        if (ModelState.IsValid)
        {
            db.UserProfiles.Add(userprofile);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(userprofile);
    }
       //
    // POST: /PostManager/Create
    public ActionResult About()
    {
        ViewBag.Message = "Your app description page.";

        return View();
    }

    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";

        return View();
    }

    // GET: /PostManager/Details/5

    public ActionResult Details(int id = 0)
    {
        UserProfile userprofile = db.UserProfiles.Find(id);
        if (userprofile == null)
        {
            return HttpNotFound();
        }
        return View(userprofile);
    }


    //
    // GET: /PostManager/Edit/5

    public ActionResult Edit(int id = 0)
    {
        UserProfile userprofile = db.UserProfiles.Find(id);
        if (userprofile == null)
        {
            return HttpNotFound();
        }
        return View(userprofile);
    }

    //
    // POST: /PostManager/Edit/5

    [HttpPost]
    public ActionResult Edit(UserProfile userprofile)
    {
        if (ModelState.IsValid)
        {
            db.Entry(userprofile).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(userprofile);
    }

    //
    // GET: /PostManager/Delete/5

    public ActionResult Delete(int id = 0)
    {
        UserProfile userprofile = db.UserProfiles.Find(id);
        if (userprofile == null)
        {
            return HttpNotFound();
        }
        return View(userprofile);
    }

    //
    // POST: /PostManager/Delete/5

    [HttpPost, ActionName("Delete")]
    public ActionResult DeleteConfirmed(int id)
    {
        UserProfile userprofile = db.UserProfiles.Find(id);
        db.UserProfiles.Remove(userprofile);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        db.Dispose();
        base.Dispose(disposing);
    }

}

3. 다음과 같이 두 개의 뷰를 포함하도록 인덱스 페이지를 편집합니다. 하나는 추가 용이고 다른 하나는 검색 용입니다.

        @using System.Linq;
    @model  workingOnAddPost.Entity.UserProfile
    @{

    };

    @*<p>*@

<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script src="~/Scripts/masonry.pkgd.min.js"></script>
<script src="~/Scripts/myScript.js"></script>

<link href="~/Content/Styles/font-awesome.css" rel="stylesheet" />
<link href="~/Content/Styles/main.css" rel="stylesheet" />
@*<div class="Button addcontent">
      <button type="button" >
          <em class="icon-plus"></em>
      </button>
</div>*@

@

@

    @section featured {
        <section class="featured">
            <div class="content-wrapper">
                <hgroup class="title">
                    <h1>@*ViewBag.Title.*@</h1>
                    <h2>@*ViewBag.Message*@</h2>
                </hgroup>
                <p>
                    To learn more about ASP.NET MVC visit
                    <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
                    The page features <mark>videos, tutorials, and samples</mark> to help you get the most from ASP.NET MVC.
                    If you have any questions about ASP.NET MVC visit
                    <a href="http://forums.asp.net/1146.aspx/1?MVC" title="ASP.NET MVC Forum">our forums</a>.
                </p>
            </div>
        </section>
    }

    <div class="Button addcontent">
        <button type="button">
            <em class="icon-plus"></em>
        </button>
    </div>

        @using (Html.BeginForm())
            {
            @Html.ValidationSummary(true)


            <div class="modal-addcontent">
                <div class="modal">
                    <div class="standardForm">
                        <h1>
                            Add new content
                        </h1>
                        <ul>
                            <li>
                                <h3>
                                    <label>
                                        Id=
                                    </label>
                                </h3>
                                <div class="editor-field">
                                    @Html.EditorFor(model => model.UserId)
                                    @Html.ValidationMessageFor(model => model.UserId)
                                </div>
                            </li>
                            <li>
                                <h3>
                                    <label>
                                        Name:
                                    </label>
                                </h3>
                                <div class="editor-field">
                                    @Html.EditorFor(model => model.UserName)
                                    @Html.ValidationMessageFor(model => model.UserName)
                                </div>
                            </li>
                            <li>
                                <h3>
                                    <label>
                                        Description
                                    </label>
                                </h3>

                                <div class="content">
                                    @Html.TextAreaFor(model => model.PostContent)
                                    @Html.ValidationMessageFor(model => model.PostContent)
                                </div>
                            </li>
                            <li>
                                <h3>
                                    <label>
                                        Image
                                    </label>
                                </h3>
                                <div>
                                    <input id="upload" type="file" />
                                </div>
                            </li>
                        </ul>
                        <div class="formFooter">
                            <div class="FooterButtons">
                                <button class="Button btn close-modalpopup" type="button">
                                    <span class="buttonText">
                                        Cancel
                                    </span>
                                </button>
                                <p>
                                    <button class="Button primary btn" type="submit" value="Create">
                                        <span class="buttonText">
                                            Create
                                        </span>
                                    </button>

                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            }
<h3>We suggest the following:</h3>
<ol class="round">
    <li class="one">
        <h5>Getting Started</h5>
        ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
        enables a clean separation of concerns and that gives you full control over markup
        for enjoyable, agile development. ASP.NET MVC includes many features that enable
        fast, TDD-friendly development for creating sophisticated applications that use
        the latest web standards.
        <a href="http://go.microsoft.com/fwlink/?LinkId=245151">Learn more…</a>
    </li>

    <li class="two">
        <h5>Add NuGet packages and jump-start your coding</h5>
        NuGet makes it easy to install and update free libraries and tools.
        <a href="http://go.microsoft.com/fwlink/?LinkId=245153">Learn more…</a>
    </li>

    <li class="three">
        <h5>Find Web Hosting</h5>
        You can easily find a web hosting company that offers the right mix of features
        and price for your applications.
        <a href="http://go.microsoft.com/fwlink/?LinkId=245157">Learn more…</a>
    </li>
</ol>
@*<table>*@
@foreach (var item in Model.UserProfilesCollection)
{

    <div id="main">
        <div id="main-inner">
            <div id="container" class="js-masonry" data-masonry-options='{ "columnWidth": ".grid-sizer", "itemSelector": ".item"}'>
                <div class="grid-sizer">
                <div class="item open-modal">
                    <p>
                        @Html.DisplayTextFor(Modelitem => item.PostContent)
                    </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
}
        @* </table>*@

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관