Model after post not change why - asp.net-mvc

I have Page for Both Insert User and this work fine but after I insert new info i send new model but this not work.the info that i insert before are still in textbox without any error. why???
return View(new User());
#using (#Html.BeginForm("RegisterUser", "UserManagement", FormMethod.Post))
{
#Html.AntiForgeryToken()
<table class="Registertbl">
<tr>
<td>نام*</td>
<td> #Html.TextBoxFor(m => m.FName, new { maxlength = 20})<br />
</td>
<td>سمت*</td>
<td>#Html.TextBoxFor(m => m.Post, new { maxlength = 200})</td>
</tr>
</table>
<br />
<input type="submit" value="Insert" class="insertBtn" />
#Html.ActionLink("back", "ViewUserList", "UserManagement")
}
//Controller
[HttpGet]
public ActionResult RegisterUser()
{
return View(new User());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RegisterUser(Common.UsersManagement.Entities.User model)
{
SetUserManagement();
var Result = userManagement.RegisterUser(model);
if (Result.Mode == Common.Extensions.ActionResultMode.Successfully)
{
return View(new User());
}
// if not Successfull
return View(model);
}

maf748 is correct, you should Post-Redirect-Get. You can communicate to the GET action method using TempData that a message should be displayed, e.g.
TempData.Message = "User registered.";
return RedirectToAction( "RegisterUser" );
Then in your RegisterUser view you can check if TempData.Message has a value.
However, if after all that you still want do do it your way you could try ModelState.Clear() before returning the new View. The problem this will cause is that if the user refreshes the page in their browser it will send them back to your Post method, prompting them in the browser with that awful "do you want to resubmit your data" message and potentially creating duplicate registrations in your database.

Try redirecting back to the GET RegisterUser.
The reason is: when you submit a form to MVC, all the values in the ModelState (basically the Request values) take precedence over any model you pass to the view. The redirect will give you an empty ViewDataDictionary, so all values will be pulled from the Model you're passing (the new User())
if (Result.Mode == Common.Extensions.ActionResultMode.Successfully)
{
return RedirectToAction("RegisterUser");
}

Related

Why the controls are not getting cleared after i pass empty object to the view in MVC?

suppose i have a form like this
#using (Html.BeginForm("submit", "home", FormMethod.Post))
{
#Html.TextBoxFor(x => x.firstname, new { placeholder = "firstname" })
#Html.TextBoxFor(x => x.lastname, new { placeholder = "lastname" })
<input type="submit" value="submit" />
}
and i have the method as follows
public ActionResult Index()
{
return View(new student());
}
[HttpPost]
public ActionResult submit(student _student) {
return View("index", new student());
}
my question is when i make a post request to the same method ie. index by passing an empty object, the controls are getting cleared but when i make a post request to the submit method the value of the controls is not getting cleared. why is that happening? why do i have to clear it using
ModelState.Clear() but not by passing any empty object?

ASP.NET MVC 5: passing POST data between views

I'd like to ask a very simple question from a rookie. I want to pass data from view Alpha.cshtml, into controller HomeController.cs with action Beta(), and then display this data in view Beta.cshtml.
Here's my Alpha.cshtml:
#using (Html.BeginForm("Beta", "Home", null, FormMethod.Post, null))
{
#Html.TextBox("data")
<input type="submit" value="Submit" />
}
Here's my Beta.cshtml:
<p>The submitted value is: #ViewBag.Data</p>
And here's my Beta() action:
public ActionResult Beta()
{
ViewBag.Data = ???
return View();
}
What do I put in place of the ???
Thanks!
When the form is submitted, all form input fields will be posted to the server. ModelBinding will take care of reading the posted values and supplying them to your action method in the list of parameters.
[HttpPost]
public ActionResult Beta(string data)
{
ViewBag.Data = data
return View();
}

How to insert a record in MVC4?

How to insert a record in MVC4 with Entity Framework?
here is my viewpage:
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.brand_id)
</td>
<td>
#Html.DisplayFor(modelItem => item.brand_name)
</td>
<td>
#Html.ActionLink("ADD", "BrandList", new { item.brand_id })
</td>
</tr>
}
here is my controller code:
public ActionResult BrandList()
{
return View(db.brand.ToList());
}
[HttpPost]
public ActionResult BrandList(int id)
{
lovelist Add_Brand = new lovelist();
Add_Brand.lovelist_member = (int)Session["Member_ID"];
Add_Brand.lovelist_brand = id;
db.lovelist.Add(Add_Brand);
db.SaveChanges();
return RedirectToAction("BrandList");
}
This is what I did so far.
I cannot insert a record to my DB.
There's no any error message. I still cannt insert a record to my DB.
You have 2 actions on your controller called BrandList. The second is decorated with the [HttpPost] attribute meaning that it can only be invoked using the POST verb. But in the code you have shown you have only a hyperlink:
#Html.ActionLink("ADD", "BrandList", new { item.brand_id })
In HTML a hyperlink (anchor) sends GET request. So basically when you click on this link you are invoking the first action which doesn't do any DB saving. If you wanted to invoke the second action using a hyperlink you should rename it (because you cannot have 2 actions with the same name accessible with the same verb) and remove the [HttpPost] attribute from it:
public ActionResult SaveBrandList(int id)
{
lovelist Add_Brand = new lovelist();
Add_Brand.lovelist_member = (int)Session["Member_ID"];
Add_Brand.lovelist_brand = id;
db.lovelist.Add(Add_Brand);
db.SaveChanges();
return RedirectToAction("BrandList");
}
You will obviously need to adapt your view as well:
#Html.ActionLink("ADD", "SaveBrandList", new { item.brand_id })
There's also a possibility to use an AJAX link which would allow you to send a POST request:
#Ajax.ActionLink("ADD", "BrandList", new { item.brand_id }, new AjaxOptions { HttpMethod = "POST" })
You will need to include the jquery.unobtrusive-ajax.js script in your view for this to work. Also since you are using an AJAX call now, there's no need to be redirecting anymore from your POST controller action but simply return some partial view or JSON that could be used on the client to refresh some portion of the page.
You have missed parameter name in id and controllername . please change your action-link to
#Html.ActionLink("ADD", "BrandList","ControllerName", new {id = item.brand_id })

MVC Parent Child actions page rendering?

I am learning to embed a child action inside a parent action, and render the whole page properly when a form is submitted from the child action.
ParentAction.cshtml--------------------------------------
#model Web1.Models.ParentActionModel
#{ViewBag.Title = "ParentAction";}
<h2>Parent Action</h2>
#Html.ValidationSummary(true, "Please correct parent errors and try again.")
#using (Html.BeginForm()) {
//parent forminput stuff
<input type="submit" value="Parent Button" />
}
#Html.Action("ChildAction","Home") <!-- ChildAction is included here -->
ChildAction.cshtml (included in parent.cshtml) ------------
#model Web1.Models.ChildActionModel
#{ViewBag.Title = "ChildAction";}
<h2>Child Action</h2>
#Html.ValidationSummary(true, "Please correct child errors and try again.")
#using (Html.BeginForm("ChildAction", "Home")) {
//child form input stuff
<input type="submit" value="Child Button" />
}
HomeController.cs-----------------------
public ActionResult ParentAction() {
return View();
}
[HttpPost]
public ActionResult ParentAction(ParentActionModel pmodel) {
//do model update stuff
return View(pmodel);
}
[ChildActionOnly]
public ActionResult ChildAction() {
return PartialView();
}
[HttpPost]
public ActionResult ChildAction(ChildActionModel cmodel) {
//do model update stuff
return PartialView(cmodel); // <---This is wrong, What's the correct way to do it?
}
Now, when I click the "Child Button", I will only get the view of the child action (durrr!), how do I fix it to generate full page parent+children view? It seems like a logic easy enough, but I am stuck on it for hours.
So, if I removed the [ChildActionOnly] in HttpPost Details method,
when I click submit, only the Details.cshtml partialView is returned,
not with the Master.cshtml, which is not what I want, neither.
That's because you should not return a PartialView in this case, but a full View:
[HttpPost]
public virtual ActionResult Details(DetailsModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
return RedirectToAction("Success");
}
You might also need to only conditionally render the Details action to avoid infinite loops:
#if (!IsPost)
{
#Html.Action("Details", "Home")
}
Obviously if you want to preserve the original context you were in when you invoked this POST action, you will have to use AJAX and then invoke this POST action with AJAX and replace only the corresponding part of the DOM.

Why is my Account Register view not working?

I'm having problem getting my view to display. I'm creating a link
#Html.ActionLink("Add as user", "Register", "Account")
but when I click on it, I'm getting this message:
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Account/Register
Here's my view:
#model ContactWeb.Models.SimpleUser
#{
ViewBag.Title = "CreateUser";
}
<h2>Create User</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true);
<fieldset>
<legend>Create User</legend>
<div>
#Html.LabelFor(c=>c.Username, "User Name")
#Html.TextBoxFor(c=>c.Username)
#Html.ValidationMessageFor(c=>c.Username)
</div>
<div>
#Html.LabelFor(c=>c.Password, "Password")
#Html.TextBoxFor(c=>c.Password)
#Html.ValidationMessageFor(c=>c.Password)
</div>
<div>
#Html.LabelFor(c=>c.ConfirmPassword, "Confirm Password")
#Html.TextBoxFor(c=>c.ConfirmPassword)
#Html.ValidationMessageFor(c=>c.ConfirmPassword)
</div>
<p>
<input type="submit" value="Register" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "List")
</div>
and my controller is
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, null, null, null, true, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
FormsAuthentication.SetAuthCookie(model.UserName, false);
return RedirectToAction("List", "Contact");
}
else
{
ModelState.AddModelError("", "The username or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
You do want an overload of the Register method for the initial GET request, but it should not have any parameters:
[HttpGet]
public ActionResult Register()
{
return View(new RegisterModel());
}
[HttpPost]
public ActionResult Register(RegisterModel model)
{
// your existing implementation here that
// checks ModelState and creates the user record
}
This will allow displaying a form with empty/default values when first loading the /Account/Register URL. This will prevent the "already defines a method with the same parameter types" and thus allow the code to compile. Also, I think you will find this advantageous to having just one Register method with no HttpPost attribute because it allows you to have a separate POST-only method to implement the postback logic, and a simpler GET-only method for the initial display. You could even customize the GET-only display to populate the model/view with certain initial values, etc.
Your register action is decorated with [HttpPost] attribute, that means that action can handle only HTTP POST requests. Ordinary links make GET requests, and as there's no handler for GET, you get 404 - not found. To fix this, create another action that will handle GET requests
[HttpGet]
public ActionResult Register()
{
return View();
}
This action will return page, with registration form on it.

Resources