我在一个视图中混合了创建视图和索引视图代码。那么,如何在asp.net MVC4中通过该视图从数据库中检索数据?

时间:2015-08-13 14:23:02

标签: c# asp.net-mvc asp.net-mvc-4 razor

我在一个视图中合并了两个视图(一个用于创建,另一个用于显示)。因此,新视图将能够同时添加和检索数据。 但它只能在数据库中创建一个新行而不检索任何内容。数据库中有4行。

这是我的新观点(索引):我添加了h1>工程/ H1>确保foreach工作

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);
        }

    }

2 个答案:

答案 0 :(得分:3)

在您的帖子操作中,您没有在视图模型上为MovieCollection设置值。此信息无法在请求中存活,您甚至不接受帖子中的完整视图模型,如果有的话。因此,您只需在返回视图之前重新填充帖子操作中的列表。

答案 1 :(得分:2)

<强> 1。在实体文件夹的模型中添加可用的行列表以与foreach一起使用:

public class RVAdapter extends RecyclerView.Adapter<RVAdapter.ViewHolder> {

    private ViewGroup parseParent;
    private Context context;
    public Button voteUp;
    private RVAdapter recyclerAdapter = this;
    private ParseQueryAdapter<ParseObject> parseAdapter;



    public RVAdapter(Context context, ViewGroup parentIn) {
        super();
        this.context = context;


        // performance optimization for recycler view
        setHasStableIds(false);


        parseParent = parentIn;
        parseAdapter = new ParseQueryAdapter<ParseObject>(context, getImagesQueryFactory()) {


            @Override
            public View getItemView(ParseObject object, View v, ViewGroup parent) {
                if (v == null) {
                    v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
                }
                super.getItemView(object, v, parent);


                final ParseImageView Image = (ParseImageView) v.findViewById(R.id.list_item_image);
                final ParseFile imageFile = object.getParseFile("img");
                if (imageFile != null) {
                    //Get singleton instance of ImageLoader
                    ImageLoader imageLoader = ImageLoader.getInstance();
                    //Load the image from the url into the ImageView.
                    imageLoader.displayImage(imageFile.getUrl(), audioImage);
                }//end if


                voteUp= (Button) v.findViewById(R.id.like);
                voteUp.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        voteUp.setEnabled(false);
                        voteUp.setText("voted Up");
                    }
                });
                return v;
            }
        };//end parseAdapter


        loadImages();
        parseAdapter.addOnQueryLoadListener(new OnQueryLoadListener());
        parseAdapter.loadObjects();
    } //end of RVAdapter

    private ParseQueryAdapter.QueryFactory<ParseObject> getImagesQueryFactory() {

        return new ParseQueryAdapter.QueryFactory<ParseObject>() {
           //Query details.....
                return query;
            }
        };
    }

    public void loadImages() {
        ParseQuery<ParseObject> query = ParseObject.getQuery();
        query.findInBackground(new FindCallback<ParseObject>() {
            @Override
            public void done(List<ParseObject> list, com.parse.ParseException e) {
                if (e == null) {
                    notifyDataSetChanged();
                } else {
                    //error
                }

            }
        });
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        parseAdapter.getView(position, holder.itemView, parseParent);

    }

    @Override
    public int getItemCount() {
        return parseAdapter.getCount();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {



        public ViewHolder(View itemView) {

            super(itemView);



            });

        }
    }

    public class OnQueryLoadListener implements ParseQueryAdapter.OnQueryLoadListener<ParseObject> {

        public void onLoading() {

        }

        public void onLoaded(List<ParseObject> objects, Exception e) {
            recyclerAdapter.notifyDataSetChanged();
        }
    }
}

<强> 2。编辑家庭控制器,使其处理httpPost和httpGet请求

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; }

3.编辑索引页面以包含两个视图,一个用于添加,另一个用于检索,如下所示:

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);
    }

}

@

@

        @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>*@