简体   繁体   中英

MVC: Data not being passed from controller to view

I need to pass object data from a controller to a view. What's supposed to happen is for the view to create an object and populate the object with data passed to it from the view. In reality, the object gets populated with null values. I've tried changing the @model statement to be @model web2.Controllers.AboutUsController , but that caused an error. The application is set up to expect the user model. I'm not sure what the problem is, as I have other places in the application where I'm passing data from controllers to views that are set up exactly like this, and I'm having no problems with those. Thanks for any help, I really appreciate it.

Here is the relevant part of the controller:

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

namespace web2.Controllers
{
    public class AboutUsController : Controller
    {
        // GET: AboutUs
        public ActionResult Index()
        {
            // create user object
            Models.User u = new Models.User();
            u.Email = "esmith@myemail.com";
            u.FirstName = "Ethan";
            u.LastName = "Smith";

            return View(u);
        
        }
    }
}

And here is the entire view:

@model web2.Models.User

<style>
    .user-image-container {
        height: unset;
    }
</style>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<img src="/wapp2-malloye/Content/Images/Ethan Pic.jpg" alt="An awesome picture of Ethan">

@{
    web2.Models.User u = new web2.Models.User();
}

<ul>
    <li>First Name: @u.FirstName </li>
    <li>Last Name: @u.LastName  </li>
    <li>Email Address: @u.Email </li>
</ul>

@using (Html.BeginForm(FormMethod.Post))
{
    <div class="section">
        <button type="submit" value="more" name="btnMore" id="More"><i class="far fa-info-circle"?></i></button>
        <button type="submit" value="close" name="btnClose" id="Close"><i class="fa fa-times"></i></button>
    </div>

}

And finally, since it's too long to include here, is a pastebin link for the user class referenced: https://pastebin.com/ayZjxRHh .

Fix the View

Remove this

@{
    web2.Models.User u = new web2.Models.User();
}

and fix form

@using (Html.BeginForm(FormMethod.Post))
{
<ul>
    <li>First Name: @Model.FirstName </li>
    <li>Last Name: @Model.LastName  </li>
    <li>Email Address: @Model.Email </li>
</ul>


    <div class="section">
        <button type="submit" value="more" name="btnMore" id="More"><i class="far fa-info-circle"?></i></button>
        <button type="submit" value="close" name="btnClose" id="Close"><i class="fa fa-times"></i></button>
    </div>

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM