barak
barak

Reputation: 179

How to pass values from action result to view

I need to pass model properties from the action to the view, Some of my model properties going to be filled by user and some by my code.

This is my model

public class DocOnDemandModel
{
    public string Domain { get; set; }
    public DateTime Time { get; set; }
    [Required]
    [Display(Name = "Name")]
    public string Name { get; set; }
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }
    [Required]
    [Display(Name = "Phone number")]
    public string PhoneNumber { get; set; }
    public string PdfUrl { get; set; }
    public string PageUrl { get; set; }
}

This is the action code

public class DocOnDemandController : Controller
{
    // GET: Request
    public ActionResult Index(string PdfUrl)
    {
        string Domain = Request.UrlReferrer.Host;
        string PageUrl = Request.UrlReferrer.OriginalString;
        DateTime Time = DateTime.Now;

        ViewBag.PageUrl = PageUrl;
        ViewBag.Domain = Domain;
        ViewBag.PdfUrl = PdfUrl;
        ViewBag.Time = Time;

        return View();
    }
}

Name, Email and Phone number will be filled by user, Domain, Time, pdfUrl, PageUrl will be filled by my action code

Now I need to pass Domain, Time, pdfUrl and PageUrl to the View and I tried with ViewBag but an error appearred

my view:

Can someone help me figure the problem and help me fix it?
Thanks in advance

Upvotes: 0

Views: 1551

Answers (3)

barak
barak

Reputation: 179

I manage to handle it this way enter image description here

Not sure if it's the right way but it's doing the job, My code remains the same.

Upvotes: 0

mohi
mohi

Reputation: 64

@Html.Label((string)ViewBag.Domain)

Upvotes: 0

Rahul Nikate
Rahul Nikate

Reputation: 6337

You can directly pass model to view from action method.

public ActionResult Index(string PdfUrl)
{
    var model = new DocOnDemandModel();
    string Domain = Request.UrlReferrer.Host;
    string PageUrl = Request.UrlReferrer.OriginalString;
    DateTime Time = DateTime.Now;

    model.PageUrl = PageUrl;
    model.Domain = Domain;
    model.PdfUrl = PdfUrl;
    model.Time = Time;

    return View(model);
}

Then in your view:

@Html.LabelFor(m => m.Domain);

Upvotes: 4

Related Questions