Home > Software design >  How to pass data from Controller to WebForm in ASP.NET MVC?
How to pass data from Controller to WebForm in ASP.NET MVC?

Time:01-09

I am trying to learn ASP.NET MVC and ADO.NET. I am making a demo website in which there would be an admin panel. The admin would update the Daily Messages which will get reflected in the main homepage. I am using ASP.NET MVC. I have created the table in database as

create table DailyMsg
(
    Sno int primary key, 
    msg varchar(max)
);

This is my Daily Access Layer

public class DailyMsgs
{
    static string connectionString = @"data source = DELL\SQLEXPRESS01;initial catalog = amen; persist security info=True;Integrated Security = SSPI;";
    SqlConnection con = new SqlConnection(connectionString);

    DailyMsg dm = new DailyMsg();

    public string ViewDailyMessage()
    {
        SqlCommand com = new SqlCommand("sp_viewDsilyMSg", con);
        com.CommandType = CommandType.StoredProcedure;
        con.Open();
        string simpleValue = com.ExecuteScalar().ToString();
       
        con.Close();
        return simpleValue;
    }
}

My model class:

public partial class DailyMsg
{
    public int Sno { get; set; }
    public string msg { get; set; }
}

Now, I am stuck at this step. I don't know how to place this returned value simpleValue to the <h2> tag of my view.

My controller

DailyMsgs dailyMsgs = new DailyMsgs();

private amenEntities db = new amenEntities();

// GET: DailyMsgs
public ActionResult Index()
{
    return View();
}

My home page:

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

CodePudding user response:

Don't use webforms with MVC, use views instead.

  1. Create a view called Index.cshtml in the Views/Home directory. Or use the easy way - just right-click the Index() action in the controller and select Add View...
  2. Currently, dailyMsgs.ViewDailyMessage() returns a string. You'll need to convert it to your model:
    // GET: DailyMsgs
    public ActionResult Index()
    {
        DailyMsg dailyMsg = new DailyMsg();
        // here I'm assuming your stored proc returns the daily message without the id
        // you should update ViewDailyMessage() to return a DailyMsg
        dailyMsg.msg = dailyMsgs.ViewDailyMessage();
        return View(dailyMsg);
    }
    
  3. At the top of the Index view add
    @model @<YourProjectName>.<Models>.DailyMsg
    
    and replace <YourProjectName>.<Models> with the actual namespace where DailyMsg class resides
  4. Add the html:
    <div>
        @Model.msg
    </div>
    

The text should be displayed inside the div.

Ideally, you should update ViewDailyMessage() in the data layer to return your DailyMsg model rather than a string.

  •  Tags:  
  • Related