Pass Value from Controller to View by ViewBag - c#

So I have a controller and I can seem to understand how to pass a parameter to my ActionResult method.
routes.MapRoute(
name: "MyRoute",
url: "{controller}/{name}/{id}",
defaults: new { controller = "Project", name = "Search", id = UrlParameter.Optional }
);
This is my route. Now in my controller i've created a method
[HttpGet]
public ActionResult Search()
{
return View();
}
[HttpPost]
public ActionResult Search(int Id)
{
ViewBag.iD = Id;
return View();
}
And in my view
<body>
<div>
ASDF + #ViewBag.iD
</div>
</body>
How can I pass a value to my iD parameter from Search Action? It seems whatever I call
http://localhost:52992/Project/Search/id=2
or http://localhost:52992/Project/Search/1
Both method go into the Search() method, none goes to Search(int iD).
What Am I missing?

A link in your view (or a form with FormMethod.Get or entering a url in the address bar) makes a GET call, not a POST, so your method should be
[HttpGet]
public ActionResult Search(int ID)
{
// do something based on the value of ID
ViewBag.iD = ID;
return View();
}
and delete the [HttpPost] method.

You have to pass value from the HttpGet 'SearchAction' method. if you pass from it, then only the value will be shown in the view
[HttpGet]
public ActionResult Search()
{
ViewBag.iD = your Id value here;
return View();
}
on intial load the get method will be called, on submission only the 'post' method will be call.
hope this helps.

On your view
<a href='#Url.Action("ActionName", "ControllerName", new { id= 10})'>...</a>
OR
#{
int id = 10
}
...
On Your Action
Public ActionResult Search(int id)
{
Viewbag.Id = id;
return view();
}
Action is by default on [HTTPGET] you wont have to mention it

Related

(Html.DropdownList) Value cannot be null. Parameter name: items

I have a Login View Page with 2 partial views _LoginPartial and _RegisterPartial. And in _RegisterPartial I have dropdownlist that contains the roles.
#Html.DropDownListFor(m => m.CompanyProfile, new SelectList(ViewBag.CompanyProfiles, "AccountId", "AccountName"), "Select", new { #class = "form-control" })
I'm initializing this dropdownlist in the GET Method as
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.CompanyProfiles = util.GetCompanyProfiles();
ViewBag.ReturnUrl = returnUrl;
return View();
}
and my code for getting the list from database is
public List<abo_AccountType> GetCompanyProfiles()
{
List<abo_AccountType> companyProfiles = new List<abo_AccountType>();
companyProfiles = db.GetAccountTypes().ToList();
return companyProfiles;
}
The list is initialized when we open the Login Page and I know that I need to initialize the dropdownlist again in the POST method, so I'm doing that just like I did it in the GET Method
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterViewModel model)
{
ViewBag.CompanyProfiles = util.GetCompanyProfiles();
if (ModelState.IsValid)
{
ViewBag.CompanyProfiles = util.GetCompanyProfiles();
string[] errors = util.CheckDuplicateAccount(model);
if (errors == null)
{
long currentUser = Convert.ToInt64(System.Web.HttpContext.Current.User.Identity.GetUserId());
util.CreateNewAccount(model, currentUser);
}
else
{
AddErrors(errors);
}
}
return RedirectToAction("Login");
}
Even though I'm initializing the dropdown again I still get the error that Value cannot be null. Parameter name: items.
I've searched almost all the answers on SO and they all say that I need to initialize the dropdown again, which I'm doing, so why am I still getting this error.
You should generate "GET" method for Register and set CompanyProfiles in there.
[HttpGet]
[AllowAnonymous]
public ActionResult Register()
{
ViewBag.CompanyProfiles = util.GetCompanyProfiles();
return View();
}
Create another model that having both the properties of that two models and pass it in your post action.
[HttpGet]
[AllowAnonymous]
public ActionResult Register(combinedModel model)
{
ViewBag.CompanyProfiles = util.GetCompanyProfiles();
return View(model);
}

Get clicked anchor element's id property

When user click this element, I want catch id data in controller or in OnActionExecuting method in ActionFilter class.
How I can do this?
In view:
<a id="123" href="AreaName/ControllerName">TEST</a>
You could try this...
In Controller:
public ActionResult Index()
{
var model = new HomeViewModel { Id = 123 };
return View(model);
}
public void RecordClick(int id)
{
int incomingId = id;
}
In View:
#Html.ActionLink("Link Text", "RecordClick", "Home", new { id = #Model.Id }, null)
Generated HTML:
Link Text
Upon clicking link, id value will be sent to RecordClick action.
TEST
your controller
[HttpGet]
public ActionResult Index(int userid)
{
return View();
}
if you debug you should have that value

Why can't the value of ViewBag be cleared after PostBack?

My controller name is "demo". I write 2 actions with the same name "Index". The first uses [HttpGet] and the seconds is [HttpPost].
But, when I require a PostBack from View, the value of ViewBag.Name in the action [HttpGet] public ActionResult Index() {} can't be cleared.
[HttpGet]
public ActionResult Index()
{
ViewBag.Name = "HttpGet";
return View();
}
[HttpPost]
public ActionResult Index(FormCollection form)
{
ViewBag.Name = "HttpPost";
return View();
}
In RouteConfig.cs:
routes.MapRoute(
name: "newroute",
url: "demo/index/{type}",
defaults: new { controller = "demo", action = "Index", type = UrlParameter.Optional }
);
and the View:
<form method="post" action="#Url.Action("Index", "demo", new { type = #ViewBag.Name })">
<input type="submit" value="Click me" />
</form>
#ViewBag.Name
Here is my problem: When I click the button, the value of #ViewBag.Name in the page is "HttpPost". But, in URL, it's /demo/index/HttpGet
Why?
If you navigate to this page with a GET request, you're executing method Index(), and as the page is rendered the Name is HttpGet, so it will create the URL for the form action as /demo/index/HttpGet.
Later, once you press the button, you're posting to that very URL created in the previous step, but since the form is POSTing you're executing Index(FormCollection form), and that sets Name to HttpPost. The URL remains what it was generated at the previous step.
Try it :
[HttpGet]
public ActionResult Index()
{
ViewBag.Name = "HttpGet";
return View();
}
[HttpPost]
public ActionResult Index(FormCollection form)
{
ViewBag.Name = "HttpPost";
return RedirectToAction("Index");
}

Setting up mvc route

I'm trying to create a mvc application. I have a project controller, actions are below
[AllowAnonymous]
[HttpGet]
public ActionResult Index()
{
//TODO: Browse
return View();
}
[AllowAnonymous]
[HttpGet]
public ActionResult Index(long projectId)
{
using (var entity = new dixraContext())
{
var project = entity.Projects.FirstOrDefault(m => m.Id == projectId);
if (project == null)
return RedirectToAction("NotFound", "Error");
else
return RedirectToAction("Index", project.UrlName);
}
}
[AllowAnonymous]
[HttpGet]
public ActionResult Index(string projectName)
{
using (var entity = new dixraContext())
{
var project = entity.Projects.Where(m => m.Name == projectName);
return View(project);
}
}
I want to show URL's like
example.com/Project/ProjectName
But when i enter url as
example.com/Project/1
Got Error.
An error occurred while processing your request
. as response. When i enter example.com/Project/Index/1 i go into first action.
I also want to resolve project from id and redirect to usual Project/ProjectName url.
Looks like you've got conflicting routes. One way to solve this while leaving your three possible inputs would be checking your input parameter.
Also, your RedirectToAction has a string as its second parameter - that overload of RedirectToAction treats the second parameter as the controller name, not the route object:
Assuming your routes file looks ok:
routes.MapRoute(
name: "Project",
url: "Project/{projectName}",
defaults: new { controller = "Project", action = "Index" }
);
Your controller action might be:
[AllowAnonymous]
[HttpGet]
public ActionResult Index(string projectName)
{
if (string.IsNullOrWhiteSpace(projectName))
{
// return your empty view
}
int projectId;
if (int.TryParse(projectName, out projectId))
{
projectName = GetProjectNameFromDatabase(projectId);
return RedirectToAction("Index", new { projectName });
}
// return your view with your model
}
There may be a better way, but this will work.

How to return an existing view from a new action in ASP.NET MVC 4?

Noob needs help!) How can I return an existing view from a new action within the same controller?
For example I have a following code:
[HttpGet]
public ActionResult Index()
{
return View(); //returns Index.cshtml
}
[HttpPost]
public ActionResult Index(string id, string condition)
{
SomeModel.ID = id;
SomeModel.Condition = condition;
return View(SomeModel); //returns Index.cshtml delegating the model
}
public ActionResult someAction()
{
return View(); //How to make this action return Index.cshtml??
}
You can specify the view name to return:
public ActionResult someAction()
{
return View("Index");
}
public ActionResult someAction()
{
return View("Index"); //How to make this action return Index.cshtml??
}
Just add
return View("YourView");
If you want send a model to it you can do this
var model = new YourViewModel
{
}
return View("YourView", model);

Categories

Resources