MVC Preserving Model When Jumping Between Controller and Forms - model-view-controller

so I recently started project in .net MVC and have been having issues preserving data. I read somewhere that in order to do so, you have to pass the model back and forth. I tried doing this, but it still runs into issues. In my project, I have two buttons right now, getData and getData2. My view prints their true/false values. When I press one, it turns true, but if I press the other, it turns true but the other one goes to false. I want them both to stay true if I press them both.
Controller:
[HttpPost]
public ActionResult GetData(TestSite.Models.FarModels theFars)
{
theFars.HasData = true;
return RedirectToAction("FarCalc",theFars);
}
[HttpPost]
public ActionResult GetData2(TestSite.Models.FarModels theFars)
{
theFars.HasData2 = true;
return RedirectToAction("FarCalc", theFars);
}
[HttpGet]
public ActionResult FarCalc(TestSite.Models.FarModels theFars)
{
return View(theFars);
}
View:
#using (Html.BeginForm("GetData", "Home", FormMethod.Post))
{
//#Html.TextBoxFor(model => model.FarValue)
<input type="submit" value="GetData" />
}
#using (Html.BeginForm("GetData2", "Home", FormMethod.Post))
{
//#Html.TextBoxFor(model => model.FarValue)
<input type="submit" value="GetData2" />
}
#Model.HasData
#Model.HasData2
Thanks

You would need to make use of TempData object because the use of RedirectToAction returns a status code of 302, and the model binding does not exist. A good example is below.
https://www.codeproject.com/Tips/842080/How-to-Persist-Data-with-TempData-in-MVC

Related

ASP.NET MVC 3 - Posting a Form Back to the Controller

I'm new to ASP.NET MVC. I'm currently using ASP.NET MVC 3. I'm trying to create a basic form with an image button that posts data back to the controller. My form looks like the following:
MyView.cshtml
#using (Html.BeginForm())
{
#Html.TextBox("queryTextBox", string.Empty, new { style = "width:150px;" })
<input type="image" alt="Search" src="/img/search.png" value="Search" name="ExecuteQuery" />
}
MyController.cs
public class MyController: Controller
{
public ActionResult Index()
{
ViewData["CurrentDate"] = DateTime.UtcNow;
return View();
}
[HttpPost]
public ActionResult ExecuteQuery()
{
if (ModelState.IsValid)
{
return View();
}
}
}
I have verified that I'm accessing my controller code. The way I've been able to do this is by successfully printing out the "CurrentDate" associated with the ViewData. However, when I click my image button, I was assuming that my break point in the ExecuteQuery method would fire. It does not. What am I doing wrong? How do I do a simple POST in MVC?
Your form is pointing to the wrong action.
Calling Html.BeginForm() creates a <form> that POSTs to the current action (Index).
You need to pass the action name to BeginForm.
Try this one
#using (Html.BeginForm("ExecuteQuery", "MyController", FormMethod.Post))
{
#Html.TextBox("queryTextBox", string.Empty, new { style = "width:150px;" })
<input type="submit" value="Search" />
}
In your controller
public class MyController: Controller
{
public ActionResult Index()
{
ViewData["CurrentDate"] = DateTime.UtcNow;
return View();
}
[HttpPost]
public ActionResult ExecuteQuery(string queryTextBox)
{
if (ModelState.IsValid)
{
// DO SOMETHING WITH queryTextBox
return View();
}
}
}
If the image submit button is very important for you, you can still change the button background image using CSS.

MVC3 Razor: how to make a partial view conditionally loaded?

I am beginner in MVC3 and still learning. I try to write an application (MVC3 with Razor) which allows user to select files and upload/save. During upload/save process I want to simply show "wait" text as partial view. I have problem since the partial view is loaded as soon as the web application is started and I got error from HomeController - [HTtpPost] Wait method, since it can't trace the list Files in object job. OF course, the list of Files will be filled after upload. I don't know how to solve this and need your help. Thank you in advance.
My HomeController.cs :
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult UploadFile(IEnumerable<HttpPostedFileBase> attachments)
{
foreach ( var file in attachments )
{
// do something
}
return RedirectToAction("Wait");
}
public ActionResult Wait()
{
// do something
ViewBag.Message = "Wait...";
return View();
}
[HttpPost]
public ActionResult Wait(FormCollection formCollection)
{
Work job = MvcApplication.GetWork();
if ( job.Files.Any() )
{
return RedirectToAction("SubmitWork");
}
else
{
return View();
}
}
The view Index.cshtml :
#{
ViewBag.Title = "FirstTry";
}
<p>
<div id="AddFiles">
#Html.Partial("_AddFiles")
</div>
</p>
<div id ="Wait">
#Html.Partial("_Wait")
</div>
The partial view _Wait.cshtml :
#{
ViewBag.Title = "Wait...";
}
#ViewBag.Message
#using ( Html.BeginForm("Wait", "Home", FormMethod.Post, new
{
id = "waitform"
}) )
{
}
<script type="text/javascript">
window.setTimeout("document.getElementById('waitform').submit()", 1000);
</script>
The partial view _AddFiles.cshtml :
#using ( Html.BeginForm("UploadFile", "Home", FormMethod.Post, new{id = "uploadForm", enctype = "multipart/form-data"}) )
{
#(Html.Telerik().Upload().Name("attachments").Multiple(true)
.Async(async => async.AutoUpload(true) )
)
<input type="submit" value="Send" class="t-button" />
<input type="reset" value="Reset" class="t-button" />
}
MVC does not work like WebForms, client side events will not propagate to server controls (there aren't really even controls, I think Telerik blurs this line a bit and complicates the MVC experience).
You can invoke additional actions in your controller to download HTML or JSON or something, but the only way on the client side to swap HTML without having your page change (since an upload is in progress) would be to use javascript.
I'm not familiar with this Telerik control, but I think you will have to do something on the client side, not on the server side, to indicate loading progress or show a spinner.
Their API shows there is an onupload event you can listen for and possible swap to the loading div:
http://www.telerik.com/help/aspnet-mvc/telerik-ui-components-upload-client-api-and-events.html
They probably have a sample somewhere. I will see if I can dig something up, but really I think just listening for this event is your best bet and do this on the client side, not the server side.

how can i transfer information of one view to another?

i have designed a view in asp .net mvc3 off course registration form. This is very simple form having name ,father name , qualification and a submit button , after pressing submit button i want to display information by using another view. please suggest me how can i send information from one view to another view.
my controller class is :
namespace RegistrationForm.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
// ViewBag.Message = "Welcome to ASP.NET MVC!";
//return View();
return RedirectToAction("registrationView");
}
public ActionResult About()
{
return View();
}
public ActionResult registrationView()
{
return View();
}
}
}
my view is :
#{
Layout = null;
}
registrationView
Enter Name
</td>
<tr>
<td>
Enter Father Name
</td>
<td>
<input type="text" name="fname" id="fname" />
</td>
<tr>
<td>
Enter Qualification
</td>
<td>
<input type="text" name="qly" id="qly" />
</td>
</tr>
</table>
<input type="submit" value="submit" />
</div>
well, we faced this problem before, and the best way to get this to work was to define a model that this page will work with, then use this model object when posting back, or redirecting to another view.
for your case, you can simply define this model in your Models folder
ex: RegistrationModel.cs file, and define your required properties inside.
after doing so, you will need to do 2 more steps:
1- in your GET action method, create a new RegistrationModel object, and provide it to your view, so instead of:
return View();
you will need something like:
var registrationModel = new registrationModel();
return View(registrationModel);
2- Use this model as a parameter in your POST Action method, something like
[HttpPost]
public ActionResult registrationView(RegistrationModel model)
{
// your code goes here
}
but don't forget to modify the current view to make use of the provided model. a time-saver way would be to create a new dummy View, and use the pre-defined template "Create" to generate your View, MVC will generate the properties with everything hooked up. then copy the generated code into your desired view, and omit any unneeded code.
this is a Pseudo reply. if you need more code, let me know
<% using Html.Form("<ActionName>") { %>
// utilize this HtmlHelper action to redirect this form to a different Action other than controller that called it.
<% } %>
use ViewData to store the value.
just remember that it will only last per one trip so if you try to call it again, the value would have been cleared.
namespace RegistrationForm.Controllers { public class HomeController : Controller { public ActionResult Index() { // ViewBag.Message = "Welcome to ASP.NET MVC!";
ViewData["myData"] = "hello world";
//return View();
return RedirectToAction("registrationView");
}
public ActionResult About()
{
return View();
}
public ActionResult registrationView()
{
// get back my data
string data = ViewData["myData"] != null ? ViewData["myData"].ToString() : "";
return View();
}
}
And you can actually usethe ViewData value on the html/aspx/ascx after redirect to the registrationView.
For example on the registrationView.aspx:
<div id="myDiv">
my data was: <%= ViewData["myData"] %>
</div>
You could simply in you method parameter list declare the parameters with the name of the controls. For example:
The control here has an id "qly"
<input type="text" name="qly" id="qly" />
Define your method parameter list as following:
public ActionResult YourMethod(string qly)
{
//simply pass your qly to another view using ViewData, TempData, or ViewBag, and use it in the desired view
}
You should use TempData which was made exactly for it, to persist values between actions.
This example is from MSDN (link above):
public ActionResult InsertCustomer(string firstName, string lastName)
{
// Check for input errors.
if (String.IsNullOrEmpty(firstName) ||
String.IsNullOrEmpty(lastName))
{
InsertError error = new InsertError();
error.ErrorMessage = "Both names are required.";
error.OriginalFirstName = firstName;
error.OriginalLastName = lastName;
TempData["error"] = error; // sending data to the other action
return RedirectToAction("NewCustomer");
}
// No errors
// ...
return View();
}
And to send data to the view you can use the model or the ViewBag.

MVC 3 Razor view BeginForm is not posting to controller in FF, but works in IE 9

I have a form in MVC 3 razor view that I am trying to post to my controller.
I need these:
1) Post the form to the controller action.
2) The action should do something with the data &return a string status (OK if success or NOK if failed)
3) Based on the result I might redirect the user after a brief delay.
4) I also want to prevent duplicate submission (if possible)
This is how my view looks (I trimmed it):
#model <MyNameSpace.Model>
#{
ViewBag.Title = "Save";
Layout = "~/Views/Shared/MyMaster.cshtml";
}
#using (Html.BeginForm("save", "my_controller"))
{
<div>
#Html.TextBoxFor(m => m.Host, new { #style = "width: 520px" })
... set other fields on the form ...
<input type="submit" id="btnSubmit" value="Submit"/>
</div>
}
This is my controller:
public String Save(<ModelName> model)
{
return "OK";
}
This seems working in IE9. But nothing happens in FF 4 or Opera. HttpFox shows no activity.
What is missing?
Thanks
In ASP.NET MVC it is considered good practice to have your controller actions return ActionResults instead of strings. This way proper content type headers will be set, etc...
So for example:
[HttpPost]
public ActionResult Save(ModelName model)
{
return Content("OK", "text/plain");
}
or if you wanted to return some view:
[HttpPost]
public ActionResult Save(ModelName model)
{
return View("Success");
}
Your example looks kosher, so either something critical is missing from your example code, or you need to view the generated HTML to see what's missing.
Did you omit the code that actually displayed the view to the user? I'm unsure of how this would function without a bit more. I mocked up your code and put in what I considered correct.
[HttpGet]
public ViewResult Save()
{
var vm = new ModelTest();
return View(vm);
}
[HttpPost]
public ActionResult Save(ModelTest model)
{
//do stuff with model
//Set a value in TempData -- Meets requirement of storing a status
TempData["Message"] = "OK";
//RedirectToRoute -- Meets requirement of preventing multiple posts partially. Some javascript will also help with this
RedirectToRoute("routename");
}
Post happened as expected in FF 4.01/5.0
Your model looks ok, it's just the controller code appears lacking.
Hopefully this helps.

call javascript method from mvc3 controller?

i have a button on the cshtml view..its clicked every-time an item is scanned.
The user has to do it one by one and once all the items have been scanned..i want to opem/pop up a new window plus redirect him to another page.. The condition whether it was the last item..is being checked in the controller method.
How can i call a javascript to open the new window from the controller..right before my 'redirecttoaction' ?
is there a better way to do it?
Here's a sample pattern:
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// TODO Process the scanned code model.Code
if (IsLastItem())
{
model.IsLast = true;
}
return View(model);
}
and inside the view:
#model MyViewModel
#using (Html.BeginForm())
{
#Html.TextBoxFor(x => x.Code)
<input type="submit" value="OK" />
}
<script type="text/javascript">
#if (Model.IsLast)
{
<text>
window.open('#Url.Action("foo")', 'foo');
window.location.href = '#Url.Action("bar")';
</text>
}
</script>
Its not clean to call JavaScript from controller. Instead, move the logic of checking if its a last item to the client side and call appropriate controller action as appropriate.

Resources