Losing Session variable on updating values - c#

I am using asp .net 4 using mvc framework.
When I update a value, my session gets lost.
I cannot seem to figure out why. I am new to ASP.
Lets say I have Session["sValue"] (= "test").
After executing the Index(), that variable is lost
Note: It only happens if !string.IsNullOrEmpty(CallPrice) is True, so CallPrice has a value.
The Controller:
// GET: Settings
[Route("Settings")]
public ActionResult Index()
{
SettingsModel pageSettings = new SettingsModel();
string CallPrice = Request.QueryString[pageSettings.Query_CallPrice];
ViewBag.Result = "";
try
{
if (!string.IsNullOrEmpty(CallPrice))
{
pageSettings.Price = Convert.ToInt32(CallPrice);
SettingsManager.call_price = CallPrice;
ViewBag.Result = "Update Succesful.";
}
}
catch (FormatException)
{
if (!string.IsNullOrEmpty(CallPrice))
pageSettings.Price = Convert.ToInt32(SettingsManager.call_price);
ViewBag.Result = "Error Occured (Incorrect format provided)";
}
return View(pageSettings);
}
The Page:
#model Actacom3CX.Models.SettingsModel
#{
ViewBag.Title = "3CX Settings";
}
<head>
#{
if (HttpContext.Current.Session[Actacom3CX.Classes.Statics.SESSION_USERNAME] == null)
{
Response.Redirect("~/UserLogon", false);
}else
{
HttpContext.Current.Session[Actacom3CX.Classes.Statics.SESSION_USERNAME] = HttpContext.Current.Session[Actacom3CX.Classes.Statics.SESSION_USERNAME];
}
}
</head>
<div class="jumbotron" style="margin-top: 0em; padding-bottom:0.4em;padding-top:0.5em;">
<div align="center">
<h2 style="margin:0em;padding:0em;">
#ViewBag.Title
</h2>
<h3 align="center">
#{
Output.Write(ViewBag.Result);
}
</h3>
</div>
</div>
<div class="row">
<form id="settingsForm" method="get" action="~/Settings">
<input class="btn btn-default" type="text" name=#{Output.Write(Model.Query_CallPrice);} value=#{Output.Write(Model.Price);} /><b style="padding-left: 1em;">Cent per minuut</b>
<br /><br />
<input class="btn btn-default" type="submit" value="Update ยป" />
</form>
</div>
UPDATE
The Session getting lost is happening in the following piece of code, in the SettingsManager:
public static void SetSetting(string key, string value)
{
Configuration configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
configuration.AppSettings.Settings[key].Value = value;
configuration.Save();
ConfigurationManager.RefreshSection("appSettings");
}

Thanks to Hans Kesting:
It seems you are updating the web.config file. When that is updated, the webapp restarts, which causes all Sessions to get lost (even from other users!).

Related

Accessing ViewBag data from Controller

I'm still learning MVC and I don't know if it's possible or not, In my application, I'm doing an excel upload task.
So here Excel uploaded and I'm adding to those excel data to view bag and shows in the view.
for (int i = 2; i <= range.Rows.Count; i++)
{
try
{
M_Employee emp = new M_Employee();
string comName = ((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 1]).Text;
var tempCompanyId = (from c in db.CreateCompany where c.CompanyName == comName select c.Id).First();
emp.CompanyId = tempCompanyId;
emp.EmpNo = int.Parse(((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 2]).Text);
emp.EmpName = ((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 3]).Text;
string dep = ((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 4]).Text;
var tempDepId = (from d in db.CreateDepartment where d.Department == dep select d.Id).First();
emp.DepId = tempDepId;
string dessig = ((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 5]).Text;
var tempDessId = (from h in db.CreateDesignation where h.Designation == dessig select h.Id).First();
emp.DesignId = tempDessId;
employees.Add(emp);
}
catch (Exception ex)
{
ViewBag.Error = "Error in " + i + " record";
return View("Import");
}
}
if (employees !=null)
{
ViewBag.EmpList = employees;
return View("Import");
}
In the view, It shows the excel imported data the user.
So to upload these data to the database table, I have created a button with mapping the upload action result in the view
<input type="button" value="Upload" class="btn btn-success" onclick="location.href='#Url.Action("UploadEmployees", "M_Employee")'" />
In that Action I tried to call those ViewBag.EmpList to get the same data and pass to the table.
foreach (var item in ViewBag.EmpList)
{
int ComId = item.CompanyId;
int EmpNo = item.EmpNo;
string EmpName = item.EmpName;
int DepId = item.DepId;
int DesId = item.DesignId;
}
But there I'm getting an error viewbag value is null. So is there any other way to do this?
Thanks
Editing--
This is my view
#{
ViewBag.Title = "Import";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div>
#using (Html.BeginForm("Import", "M_Employee", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="card card-primary">
<div class="card-header">
<h1 class="card-title"><b>Upload Employees from Excel</b></h1>
</div>
<!-- /.card-header -->
<div>
<br />
#Html.Raw(ViewBag.Error)
<h4><span>Select Excel File</span></h4>
<input type="file" name="excelFile" class="btn btn-warning" />
<br />
</div>
<div class="row">
<div class="col-md-1">
<br />
<br />
<input type="submit" value="Import" class="btn btn-info" />
</div>
<div class="col-md-1">
<br />
<br />
<input type="button" value="Upload" class="btn btn-success" onclick="location.href='#Url.Action("UploadEmployees", "M_Employee")'" />
</div>
</div>
<div class="card-body p-0">
<table class="table table-striped">
<tr>
<th>Company</th>
<th>EmpId</th>
<th>EmpName</th>
<th>Department</th>
<th>Dessignation</th>
</tr>
#if (ViewBag.EmpList != null)
{
foreach (var item in ViewBag.EmpList)
{
<tr>
<td>
#item.CompanyId
</td>
<td>
#item.EmpNo
</td>
<td>
#item.EmpName
</td>
<td>
#item.DepId
</td>
<td>
#item.DesignId
</td>
</tr>
}
}
</table>
</div>
<!-- /.card-body -->
</div>
}
</div>
This is the view model I have created.
[NotMapped]
public class EmpExcelUploadViewModel
{
public int CompanyId { get; set; }
public int EmpNo { get; set; }
public string EmpName { get; set; }
public int EmpDep { get; set; }
public int EmpDes { get; set; }
}
You can use ViewBag or ViewData for transferring data only one-way from Controller to View.
You should resend data from client's browser to your back-end with form.
Or if user can not edit data you can use any of:
Save file on the first step, then use the identifier of uploaded earlier file, re-read it for saving
Parse file and save parsed data into storage as draft on the first step, then just remove draft mark from data on the second step
You can not use ViewBag to move data from a client computer to a server. You can use Session or TempData (if the data is small) to keep data in the server, but I don' t recommend to use it since it affects app scalability.
You have 2 ways
Repeat downloading in your upload action and save data to a database
or you have to fix the action, using model instead of viewbag
....
if (employees !=null)
{
return View("Import", employees);
}
else ... you error code
in Import view add form and replace an ancor by submit button
#model List<Employee>
#using (Html.BeginForm("UploadEmployees", "M_Employee", FormMethod.Post))
{
.... emloyee input controls
<button type="submit" value="Upload" class="btn btn-success"> </>
}
in UploadEmployees action you can get data from an input parameter and save to database.

How to capture the URL input and append it to a text box in razor pages?

I am just starting out in razor pages and I need some help with getting the user's inputted URL on a submit and appending it to a local text file. This is for testing purposes, I know it is not common practice to append to a text file.
Here is my html/razor page
#page
#model UploadModel
#{
ViewData["Title"] = "Upload a Link";
}
<h2>#ViewData["Title"]</h2>
<h3>#Model.Message</h3>
<form method="post">
<div class="textBox">
<input type="url" data-val="true" data-val-url="The Website field is not a valid fully-
qualified http, https, or ftp URL." id="input_URL" name="inputURL" value="" />
<br />
<button id="submit" type="submit" value="Submit" onclick="btnSubmit_Click()"
class="btn btn-primary" runat="server">Submit</button>
</div>
</form>
My C#/backend code
public class urlClass
{
[BindProperty]
public string userInput { get; set; }
private void OnPost()//btnSubmit_Click(object sender, EventArgs e)
{
using (StreamWriter writerURL = new StreamWriter("log.txt"))
{
urlClass urlc = new urlClass();
urlc.userInput = ;
writerURL.WriteLine(urlc.userInput);
}
}
}
}
You can try to change userInput to inputURL.Because .net core bind model with name.And you can change private void OnPost() to public void OnPost().So that it can be triggered.Here is a working demo:
cshtml:
<form method="post">
<div class="textBox">
<input type="url" data-val="true" data-val-url="The Website field is not a valid fully-
qualified http, https, or ftp URL." id="input_URL" name="inputURL" value="" />
<br />
<button id="submit" type="submit" value="Submit"
class="btn btn-primary" runat="server">
Submit
</button>
</div>
</form>
cshtml.cs:
[BindProperty]
public string inputURL { get; set; }
public void OnPost()//btnSubmit_Click(object sender, EventArgs e)
{
using (StreamWriter writerURL = new StreamWriter("log.txt"))
{
//urlClass urlc = new urlClass();
//urlc.userInput = ;
writerURL.WriteLine(inputURL);
}
}
result:
i recommand msdn.
You can solve it by looking at this example.
https://learn.microsoft.com/ko-kr/aspnet/core/razor-pages/?view=aspnetcore-5.0&tabs=visual-studio

Razor Pages async task return to modal

I'm new in Razor Pages and I can't really find a solution on my problem.
I have a modal, where I would like to update the Identity Roles(Add/Remove users). The async task works fine and I have the list for the members and nonmembers, but the modal close itself after the post.
How I can prevent it(modal close) what is the correct return in this case?
C#
public async Task<IActionResult> OnPostAddtoRoleAsync()
{
if(Input != null)
{
ToolboxRoles role = await _RoleManager.FindByIdAsync(Input.Id);
List<ToolboxUser> members = new List<ToolboxUser>();
List<ToolboxUser> nonMembers = new List<ToolboxUser>();
foreach (ToolboxUser user in _UserManager.Users)
{
var list = await _UserManager.IsInRoleAsync(user, role.Name) ? members : nonMembers;
list.Add(user);
}
Input.Role = role;
Input.Members = members;
Input.NonMembers = nonMembers;
}
return Page(); //I don't know what is the correct return action here, so the modal stay showed
}
Function calling:
<form method="post">
<button asp-page-handler="AddtoRole" asp-route-id="#item.Id" class="btn btn-default" data-id="#item.Id" data-name="#item.Name" data-toggle="modal"
data-target="#EditRole" data-backdrop="static" data-keyboard="false" style="margin-bottom: 10px;">
Update
</button>
Modal:
<div id="EditRole" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header" style="background-color: #ffd800">
<h4 class="modal-title" style="text-align:left">Update Role</h4>
</div>
<div class="modal-body" style="background-image: linear-gradient(#ffd800,#fff)">
<form method="post">
<input type="text" id="modal_name" asp-for="Input.RName" />
<input type="text" id="modal_id" asp-for="Input.Id" />
#if (Model.Input != null)
{
<div class="row">
<div class="col-md-12" style="background-image: radial-gradient(#ffd800,#fff);border: 1px solid #f11322;margin-bottom: 10px;">
<h4 id="modal_text1" class="font-weight-bold" style="color: #f11322;"></h4>
</div>
</div>
<table class="table table-bordered table-sm">
#if (Model.Input.NonMembers.Count() == 0)
{
<tr><td colspan="2">All Users Are Members</td></tr>
}
else
{
#foreach (ToolboxUser user in Model.Input.NonMembers)
{
<tr>
<td>#user.UserName</td>
<td>
<input type="checkbox" name="AddIds" value="#user.Id">
</td>
</tr>
}
}
</table>
<div class="row">
<div class="col-md-12" style="background-image: radial-gradient(#ffd800,#fff);border: 1px solid #f11322;margin-bottom: 10px;">
<h4 id="modal_text2" class="font-weight-bold" style="color: #f11322;"></h4>
</div>
</div>
<table class="table table-bordered table-sm">
#if (Model.Input.Members.Count() == 0)
{
<tr><td colspan="2">All Users Are Members</td></tr>
}
else
{
#foreach (ToolboxUser user in Model.Input.Members)
{
<tr>
<td>#user.UserName</td>
<td>
<input type="checkbox" name="DeleteIds" value="#user.Id">
</td>
</tr>
}
}
</table>
}
<button asp-page-handler="UpdateRoles" class="btn btn-default">Save</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
And the JS which I use to pass the values to the modal:
$('#EditRole').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget); // Button that triggered the modal
var id = button.data('id');
var name = button.data('name'); // Extract info from data-* attributes
// Update the modal's content
document.getElementById('modal_id').setAttribute('value', id);
document.getElementById('modal_name').setAttribute('value', name);
var modal = $(this);
modal.find('#modal_text1').text('Add Users to ' + name);
modal.find('#modal_text2').text('Remove Users from ' + name);
});
Thanks,
Devcore
return Page() you should call when you want to refresh page. If everything is OK after adding to list (you are sure that Add is performed) you can just: return Ok(), or return NoContent().
Read documentation: Microsoft docs.
I think it might be better to see the whole picture (how your modal is handling the return response from your OnPostAddtoRoleAsync() function).
as Lazar pointed out, What would be more beneficial is to return a response on whether the users were added to the roles correctly. Using Ok() or other various status codes depending on what happened to the users would be more beneficial in this instance.
You can prevent certain actions from taking place inside the modal by using event.preventDefault();. Again, we can't see how your frontend razor page is handling the modal since you have not provided that here. This source might help with using modals https://www.mikesdotnetting.com/article/349/razor-pages-and-bootstrap-modal-master-details
Let me know if this helps, thanks.
I think you should separate the modal body and make it as a partial view. Use jquery ajax to get the partial view, append it to the modal then open it.
I made a simple demo, you may refer to it.
Index.cshtml:
#page
#model IndexModel
#{
ViewData["Title"] = "Home page";
}
#Html.AntiForgeryToken()
<button id="Edit" data-id="1" class="btn btn-danger"
data-backdrop="static" data-keyboard="false" style="margin-bottom: 10px;">
Update
</button>
<div id="EditRole" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header" style="background-color: #ffd800">
<h4 class="modal-title" style="text-align:left">Update Role</h4>
</div>
<div class="modal-body" style="background-image: linear-gradient(#ffd800,#fff)">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
#section scripts{
<script>
$("#Edit").click(function () {
var id = $(this).attr('data-id');
$.ajax({
type: 'POST',
url: 'Index?handler=AddtoRole',
data: {
id: id,
},
headers: {
RequestVerificationToken:
$('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (result) {
$('.modal-body').html(result);
$('#EditRole').modal('show');
}
});
})
</script>
}
Index.cshtml.cs:
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
[BindProperty]
public Student Input { get; set; }
public void OnGet()
{
}
public IActionResult OnPostAddtoRole()
{
Input.Name = "StudentA";
return Partial("_AddRolePartial",Input);
}
public void OnPost()
{
}
}
_AddRolePartial.cshtml:
#model RazorTest.Models.Student
<form method="post">
<div>
<label>Id:</label>
#Model.Id
</div>
<div>
<label>Name:</label>
#Model.Name
</div>
<button asp-page-handler="UpdateRoles" class="btn btn-default">Save</button>
</form>
Student.cs:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
Result:

C# MVC Adding a record to a table with form and parameters

I am having an issue with my add to a database record.
What I am attempting to do is add a record with parameters sent from a form. I am grabbing an item from a table giving a quantity and them adding it to an orders table.
I am adding it to the OrderDetails table so I need the orderId. Which I grab from the Url.
Below is my code, It is not working. It could probably be simplified but I am not sure where to modify this.
Form on Page:
#{ var OrderId = Request.Url.Segments[3];}
<td>
<form method="GET" action="~/OrderManager/AddToOrder/#OrderId" _lpchecked="1">
<div class="row ">
<div class="input-group mb-3 col-xs-6 col-md-6">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default">Qty</span>
</div>
<input style="max-width:75px;" aria-label="Qty" aria-describedby="inputGroup-sizing-default" type="number" class="form-control" id="quantity" min="1" name="quantity">
</div>
<div class="col-xs-6 col-md-6">
<button class="btn btn-primary btn-sm" type="submit" id="submit" onchange="usercheck">Add To Order</button>
</div>
</div>
</form>
</td>
Here is my Controller actions:
public ActionResult Add(int id)
{
try
{
GeneralEntities db = new GeneralEntities();
var result = db.Extras.ToList().OrderByDescending(x => x.CreatedDate);
return View(result);
}
catch (Exception ex)
{
throw ex;
}
}
public ActionResult AddToOrder(int OrderId, string id, int quantity)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
try
{
GeneralEntities ExtrasDb = new GeneralEntities();
var addedExtra = ExtrasDb.Extras
.Single(ext => ext.ExtrasName == id);
var extra = new OrderDetail
{
OrderId = OrderId,
Extras = addedExtra.BillingExtrasId,
Quantity = quantity,
CreatedDate = DateTime.Now
};
ExtrasDb.OrderDetails.Add(extra);
sb.Append("Sumitted");
return Content(sb.ToString());
}
catch (Exception ex)
{
sb.Append("Error :" + ex.Message);
}
return Content(sb.ToString());
}
Thanks for your help!
Revised Code Update:
I changed some things. I seem to have what i need now and it says it submits but it does not save it to the table..
Revised form:
#{ var OrderId = Request.Url.Segments[3];}
<td>
<form method="POST" action="~/OrdersManager/Add/" _lpchecked="1">
<div class="row ">
<div class="input-group mb-3 col-xs-6 col-md-6">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default">Qty</span>
</div>
<input data-val="true" id="OrderId" name="OrderId" type="hidden" value="#OrderId" />
<input data-val="true" id="id" name="id" type="hidden" value="#item.BillingExtrasId" />
<input style="max-width:75px;" aria-label="Qty" aria-describedby="inputGroup-sizing-default" type="number" class="form-control" id="quantity" min="1" name="quantity">
</div>
<div class="col-xs-6 col-md-6">
<button class="btn btn-primary btn-sm" type="submit" id="submit" onchange="usercheck">Add To Order</button>
</div>
</div>
</form>
</td>
Revised Controller Code:
[HttpPost]
public ActionResult Add(int OrderId, Guid id, int quantity)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
try
{
GeneralEntities ExtrasDb = new GeneralEntities();
// Retrieve the album from the database
var addedExtra = ExtrasDb.Extras
.Single(ext => ext.BillingExtrasId == id);
var extra = new OrderDetail
{
OrderId = OrderId,
Extras = addedExtra.BillingExtrasId,
UnitPrice = addedExtra.Price,
Quantity = quantity,
CreatedDate = DateTime.Now
};
ExtrasDb.OrderDetails.Add(extra);
sb.Append("Sumitted");
return Content(sb.ToString());
}
catch (Exception ex)
{
sb.Append("Error :" + ex.Message);
}
return Content(sb.ToString());
}
Add
ExtrasDb.SaveChanges();
right before the first return statement inside of the try block.
(You found the mistake and mentioned it in your comment. I'm just confirming and turning it into an answer.)

ASP.NET MVC 3 form submit affects RenderAction handlers

I have control for user authorization which includes form, two textboxes and submit button.
This control included in the master page through RenderAction method.
I have registration page (its view included through RenderBody method) also with form. When I submit data from the registration form, the login control is triggered also and its handler (controller method for handling POST data) is called. Below you can see controller methods for authorization.
How can I prevent sending POST data to the login control after submitting data from other forms?
[HttpPost]
public RedirectResult LogIn(AuthViewModel authResult)
{
if (ModelState.IsValid)
{
userService.LogInUser(authResult.Login, authResult.Password, Request.UserHostAddress);
}
else
{
TempData["AuthMessage"] = GetValidationMessage();
}
string redirectUrl = "/";
if (Request.UrlReferrer != null)
{
redirectUrl = Request.UrlReferrer.AbsoluteUri.ToString();
}
return Redirect(redirectUrl);
}
[HttpGet]
[ChildActionOnly]
public PartialViewResult LogIn()
{
if (userService.IsUserLoggedIn())
{
User currentUser = userService.GetLoggedInUser();
ViewBag.LoggedInMessage = currentUser.FullName + "(" + currentUser.Login + ")";
}
return PartialView("AuthControl");
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>#ViewBag.Title</title>
</head>
<body>
<div>
<div id="header">
<div>
<div>
#{Html.RenderPartial("SearchControl");}
</div>
</div>
</div>
<div id="right_menu">
<div>
#{Html.RenderAction("LogIn", "Navigation");}
</div>
#{Html.RenderAction("Menu", "Navigation");}
<div>
#{Html.RenderAction("Index", "Messages");}
</div>
<div>
#{Html.RenderAction("TagCloud", "Navigation");}
</div>
</div>
<div id="main_content">
#RenderBody()
</div>
<div id="footer">
</div>
</div>
</body>
</html>
AuthControl:
#model AuthViewModel
<div class="rounded-corners auth-panel">
#if (ViewBag.LoggedInMessage == null)
{
<div class="auth-container">
#using (Html.BeginForm("LogIn", "Navigation"))
{
<div>
<label for="Login">
Login:
</label>
#Html.TextBoxFor(m => m.Login, new { #class="middle-field"})
</div>
<div>
<label for="Password">
Password:
</label>
#Html.PasswordFor(m => m.Password, new { #class="middle-field"})
</div>
<div class="in-center">
<input type="image" src="#Url.Content("~/Content/Images/submit.png")"/>
</div>
}
</div>
<div class="error-msg">
#if (TempData["AuthMessage"] != null)
{
#Html.Raw(TempData["AuthMessage"].ToString())
}
#Html.ValidationSummary()
</div>
<div class="small-nav-message">
Registration
</div>
}
</div>
Registration page:
RegistrationViewModel
#{
ViewBag.Title = "Registration";
}
#if (TempData["RegistrationFinished"] == null || !(bool)TempData["RegistrationFinished"])
{
<div class="post content-holder">
<div class="fields-holder">
<div >
<div class="error-msg">
#if (TempData["ValidationMessage"] != null)
{
#Html.Raw(TempData["ValidationMessage"].ToString())
}
</div>
#using (Html.BeginForm())
{
<span>
Email:
</span>
<span>
#Html.TextBoxFor(v => v.Email)
</span>
<span>
Password:
</span>
<span>
#Html.PasswordFor(v => v.Password)
</span>
<input type="submit" value="Register"/>
}
</div>
</div>
</div>
}
else
{
<div>
Activation link was sent to your email.
</div>
}
In the Registration view, change
#using (Html.BeginForm())
to
#using (Html.BeginForm("Index", "Registration"))
In a single controller, single Action scenario, the extra specific routing information is not required, but obviously the routing engine can't figure out on it's own which controller/action to route to with multiple controllers/actions.
Edit based on comments:
So this is a routing problem. Try adding a specific route for your Registration action. Something like
routes.MapRoute(
"Register", // Route name
"{controller}/Index/{registrationResult}", // URL with parameters
new {
controller = "{controller}",
action = "Selector",
registrationResult= UrlParameter.Optional
}
);
'registrationResult' would be the name of the parameter in the post Action. I'm thinking that the view models are so similar the routing engine can't differentiate between the two. Add the above route before the default route and it should match it when the registration form is submitted.
To solve my problem I check IsChildAction property from the controller context. Also I have to clear the model state.
[HttpPost]
public ActionResult LogIn(AuthViewModel authResult)
{
if (!this.ControllerContext.IsChildAction)
{
if (ModelState.IsValid)
{
userService.LogInUser(authResult.Login, authResult.Password, Request.UserHostAddress);
}
else
{
TempData["AuthMessage"] = GetValidationMessage();
}
string redirectUrl = "/";
if (Request.UrlReferrer != null)
{
redirectUrl = Request.UrlReferrer.AbsoluteUri.ToString();
}
return Redirect(redirectUrl);
}
ModelState.Clear();
return PartialView("AuthControl");
}

Categories