Asp.net mvc checkbox checked from the action - asp.net-mvc

Question: I have to check the checkbox(which is not part of model) from the action ?
If I select the checkbox and submit to post action, then call the view again the checkbox will be checked fine. But how to check it on first place from non-post action please ? Thanks!
public ActionResult Images(string params)
{
//some code
return View(cp);
}
[HttpPost]
public ActionResult Images(string chbx)
{
//some code
}
Images view:
#using (Html.BeginForm())
{
#Html.CheckBox("chbx")
}
I'm using MVC3 by the way.

do you mean #Html.CheckBox("chbx", true) ?

Related

MVC redirect to previous page (exclude not httppost action)

i have three action on controller
public ActionResult Index() {}
public ActionResult Insert() {}
[HttpPost]
public ActionResult Insert() {
//some insert code
redirect to where you come from but exclude Insert page
}
and other controller
public ActionResult Example() {}
i am going to Insert page from Index or maybe from Example then submit the form to HttpPost action. i am trying redirect to Index page or Example page (im trying to find i came from which page). how can i achieve that (UrlReferrer is redirect to Insert page)
All you need to do is ,keep track of where the request comes from. There are multiple ways to do it. Here is one
In your insert GET action method, you can read the UrlReferrer value and pass that to the view, where you will keep that inside a hidden input inside the form. When the form is submitted, you can read this in your HttpPost action method and do a redirect to that.
public ActionResult Insert()
{
ViewBag.ReturnUrl = Request.UrlReferrer;
return View(new InsertVm());
}
and in your form
#model InsertVm
#using (Html.BeginForm("Insert", "Users"))
{
<input type="hidden" name="returnUrl" value="#ViewBag.ReturnUrl" />
#Html.TextBoxFor(a=>a.EmailAddress)
<button type="submit">Send</button>
}
Now in your Insert HttpPost action, add a parameter with the same name as your hidden input
[HttpPost]
public ActionResult Insert(InsertVm model,string returnUrl)
{
// to do : Save data
if(!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
//fall back
return RedirectToAction("Index","Home");
}

Basic wizard, and passing model from one view to another?

I'm new to MVC and trying to create a wizard-style series of views, passing the same model instance from one view to the next, where the user completes a little more information on each form. The controller looks something like this:-
[HttpGet]
public ActionResult Step1()
{
return View();
}
[HttpPost]
public ActionResult Step1(MyModel model)
{
if (!ModelState.IsValid)
return View(model);
return View("Step2", model);
}
[HttpPost]
public ActionResult Step2(MyModel model)
{
if (!ModelState.IsValid)
return View(model);
return View("Step3", model);
}
// etc..
Questions:-
When I submit the form from the Step1 view, it calls the Step1 POST method and results in the Step2 view being displayed in the browser. When I submit the form on this view, it calls the Step1 POST method again! I got it to work by specifying the action and controller name in Html.BeginForm(), so I'm guessing that the parameterless overload just POSTs back to the action that rendered the view?
I've noticed that the browser's address bar is out of sync with the current view - when I'm on the Step2 view it still shows the Step1 URL, and when on Step3 it shows the Step2 URL. What's going on?
Another approach I've seen for passing a model between views is to put the model in TempData then use RedirectToAction(). What are the pros and cons of this method versus what I'm currently doing?
I won't be providing any "back" buttons of my own in the wizard. Are there any pitfalls to be aware of regarding the browser's back button, and do either of the above two approaches help (or hinder)?
Edit
Prompted by #StephenMuecke's comment I've now rewritten this to use a single view. I tried this once before but had difficulties round-tripping a "step number" to keep track of where I was in the wizard. I was originally using a hidden field created with #Html.HiddenFor', but this wasn't updating as the underlying model property changed. This appears to be "by design", and the workaround is to create the hidden field using vanilla HTML (
Anyway the one-view wizard is now working. The only problem is the old chestnut of the user being able to click the back button after they have completed the wizard, make a change, and resubmit a second time (resulting in a second DB record).
I've tried adding [OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")] to my POST method, but all this does is display (in my case) a Chrome error page suggesting that the user clicks refresh to resubmit the form. This isn't user friendly and doesn't prevent a second submit.
you can use RedirectToAction() in this case without worrying about TempData. Just add your model as a parameter to each action and use RedirectToAction("Step2", model);
[HttpGet]
public ActionResult Step1()
{
return View();
}
[HttpPost]
public ActionResult Step1(MyModel model)
{
if (!ModelState.IsValid)
return View(model);
return RedirectToAction("Step2", model);
}
[HttpGet]
public ActionResult Step2(MyModel model)
{
return View(model);
}
[HttpPost]
public ActionResult Step2(MyModel model)
{
if (!ModelState.IsValid)
return View(model);
return RedirectToAction("Step3", model);
}
// etc..
The answer to #1 is found in #2.. if you dont specify the Action in you Html.BeginForm() it posts to the current url.
Using TempData to avoid model displaying in url.
[HttpGet]
public ActionResult Step1()
{
return View();
}
[HttpPost]
public ActionResult Step1(MyModel model)
{
if (!ModelState.IsValid)
return View(model);
TempData["myModel"] = model;
return RedirectToAction("Step2");
}
[HttpGet]
public ActionResult Step2()
{
var model = TempData["myModel"] as MyModel;
return View(model);
}
[HttpPost]
public ActionResult Step2(MyModel model)
{
if (!ModelState.IsValid)
return View(model);
TempData["myModel"] = model;
return RedirectToAction("Step3");
}
// etc..
Another option would be to add the name of the next action to ViewBag and set your actionName in each BeginForm()
[HttpGet]
public ActionResult Step1()
{
ViewBag.NextStep = "Step1";
return View();
}
[HttpPost]
public ActionResult Step1(MyModel model)
{
if (!ModelState.IsValid)
{
ViewBag.NextStep = "Step1";
return View(model);
}
ViewBag.NextStep = "Step2";
return View("Step2", model);
}
[HttpPost]
public ActionResult Step2(MyModel model)
{
if (!ModelState.IsValid)
{
ViewBag.NextStep = "Step2";
return View(model);
}
ViewBag.NextStep = "Step3";
return View("Step3", model);
}
//View
#using (Html.BeginForm((string)ViewBag.NextStep, "ControllerName"))
{
}
I'd prefer to add NextStep as a property to MyModel and using that instead of using ViewBag though.
I understand the thought behind your approach and don't have any issues with it. Unfortunately, I don't believe that ASP.NET MVC is geared very well for passing the the same view model (with data!) between different actions.
Typically, the scaffolded actions in the controller will either create a model item or find it by identifier in the database.
I don't know if this would help, but you could try to save it to the database on every step, and then retrieve it by identifier, or you could also save it to a session and grab it that way.
One issue I do see with your approach is you have Step2 set as a get, yet you probably want to post data to it from Step1 instead of using a query string. You may need to reconcile that issue.

asp.net mvc hyperlink a page?

I have a mvc project and I need to link a page using a hyperlink.I tried like this
<div class="someclass">1</div>
but its showing page cannot displayed error.What can be the reason?
structure is Views> Home > mylinkpage.cshtml
Thanks
Action is a method in a controller.
You should have.
public class HomeController : Controller
{
public ActionResult mylinkpage(string id)
{
return View();
}
}
Alternate you can try
#Html.ActionLink("1", "mylinkpage","Home", new { }, new { #class = "something" })

ASP.Net MVC sending model to view without using URL

I am using the same model between 2 views, but when posting the model to the second view it puts all the previously entered data in the URL. Is it possible to send the populated model to the second view without posting the data in the URL?
Controller code:
[HttpPost]
public ActionResult ViewExample1(.Models.RegisterModel model)
{
if (ModelState.IsValid)
{
return RedirectToAction("ViewExample2", model);
}
return View(model);
}
public ActionResult ViewExample2(Models.RegisterModel model)
{
return View(model);
}
Second view code where I use HiddenFor to persist the data when this view is posted back:
<% using (Html.BeginForm(null, null, FormMethod.Post, new { id="ViewExample2"})) { %>
<%: Html.HiddenFor(model => model.UserName)%>
<% } %>
When you redirect to an action with RedirectToAction(), you're doing that by GET. So the Framework passes your view model in the url to the action.
I'd suggest you to do this:
[HttpPost]
public ActionResult ViewExample1(Models.RegisterModel model)
{
if (ModelState.IsValid)
{
// Do the work you want to do in the ViewExample2 action here!
// ... and then return the ViewExample2 view
return View("ViewExample2", model);
}
return View(model);
}
// This action is not needed anymore
/*public ActionResult ViewExample2(Models.RegisterModel model)
{
return View(model);
}*/
My guess is that you're using a form tag (rather than BeginForm) and you aren't specifying a method, so it defaults to using a GET rather than a POST.
Convert to using a BeginForm, or add the method.

MVC3 Form Posted Value

Below Scenario, I think I must see the START text in my form when first loaded.
When I click send data button and submit, I was waiting to see FINISH text in my form.
Buy the START text never changes when I click the button and post the form...
Anybody can tell the problem?
MY CONTROLLER:
namespace MvcApplication1.Controllers
{
public class BuyController : Controller
{
public ActionResult Index(BuyModel model)
{
if (Request.HttpMethod == "GET")
{
model.Message= "START";
return View(model);
}
else
{
BuyModel newModel = new BuyModel();
newModel.Message= "FINISH";
return View(newModel);
}
}
}
}
MY VIEW :
#model MvcApplication1.Models.BuyModel
#using (Html.BeginForm("Index", "Buy", FormMethod.Post))
{
#Html.TextBoxFor(s => s.Message)
<button type="submit" >Send</button>
}
MY MODEL:
public class BuyModel
{
public string Message { get; set; }
}
public class BuyController : Controller
{
public ActionResult Index()
{
BuyModel model = new BuyModel();
model.Message= "START";
return View(model);
}
[HttpPost]
public ActionResult Index(BuyModel model)
{
model = new BuyModel();
model.Message= "FINISH";
ModelState.Clear(); // the fix
return View(model);
}
}
View:
#model MvcApplication1.Models.BuyModel
#using (Html.BeginForm("Index", "Buy"))
{
#Html.TextBoxFor(s => s.Message)
<button type="submit" >Send</button>
}
Your issue is because your original code, that Action Method will only be executed as an HTTP GET request. ASP.NET MVC allows you to specify a post with the [HttpPost] attribute (see above code).
I'm not sure what you are getting at with your POST desired-behavior. It seems like you are just wiping out whatever form values are pushed on the POST. So modify my above code accordingly, but it should give you the general idea.
Edit: it seems to be that the text box is retaining its value after the POST. It's not just with "START", but if you type anything into that text box and hit submit, you'll have a POST with the exact same text in the text box that was there when you submitted the form.
Edit Edit: see the changed code. Call ModelState.Clear() in your POST action method and you'll have the right value reflected.
If you are posting, and not returning a RedirectResult, by default the helpers will use the value from ModelState. You either need to clear ModelState or have a different approach.
The PRG (post redirect get) pattern in MVC is very important. So if its a post, and you aren't redirecting, the helpers assume there is an error that needs to be corrected and the value is pulled from ModelState.

Resources