Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a string from Controller to View in ASP.NET MVC5

I have this controller :

public ActionResult MyController(string myString)
{
    return View((object)myString);
}

I'm trying to pass the string to view like this :

@model string
@Html.EditorFor(m => m)

I get value can't be null error. How can I fix this? Thanks.

like image 671
novice Avatar asked Dec 18 '25 21:12

novice


2 Answers

First of all, I would recommend to change your Action method name. Why you name it like MyController. It should be a meaningful method name.

Then come to your issue. If your view is only for display purpose, not for form post, then you can bind your string in a viewbag and render in your view.

For example, in your action method,

ViewBag.MyString = myString;

And in your view,

<p>@ViewBag.MyString</p>

But if you want to edit your string in view and after click a submit button, it should post the value to server, then create a view model, for example,

public class MyStringModel
{
  public string MyString { get; set; }
}

In your action method,

public ActionResult MyController(string myString)
{
  MyStringModel = new MyStringModel();
  MyStringModel.MyString = myString;
  return View(MyStringModel)
}

Then in your view,

@model MyStringModel
@Html.EditorFor(m => m.MyString)

See, you need to add @HTML.BeginForm and a submit button in your view to post back your string data.

Hope it helps.

like image 95
Basanta Matia Avatar answered Dec 20 '25 13:12

Basanta Matia


Also you can pass information to your view with the ViewBag, ViewData, TempData all with different information lifecyle.

Check this:

http://royalarun.blogspot.com.ar/2013/08/viewbag-viewdata-tempdata-and-view.html

With your example the model is associated with a dictionary so you can not use directly the property like this.

For your example and just pass only a string from the controller you can do any like this:

public ActionResult MyController(string myString)
{
    return View(model:myString);  
}

and in the .cshtml (if you use c#)

@model string
@{
    var text = Model;
}
@Html.EditorFor(m => text);

But I think is a better solution pass a viewMoedel with a string property like the @Stephen Muecke response Prefill Html Editor Asp.net MVC

like image 29
Dei Revoledo Avatar answered Dec 20 '25 12:12

Dei Revoledo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!