2012-10-15 209 views
1

作为MVC和淘汰赛的新手,我需要一些帮助。我试图获得一些JSON结果(作为字符串)发布到我的控制器,然后让控制器RedirectToAction到一个新的视图和操作。MVC - 将json结果发布到控制器,然后从控制器重定向

问题:即使命中RedirectToAction,控制器也总是返回相同的视图。

(它通过重定向代码,然后在最后直接回到发布视图。)我不得不放置一个“下一步”的行动,这是有点尴尬。

ALSO:隐藏字段是存储/传递ID时的最佳方式吗?

VIEW

@model WebRole.Website.Models.Registration3Model 
@{ 
ViewBag.Title = "Step 3: Adding Members"; 
} 
@using (Html.BeginForm()) 
{ 

<input name="GroupID" id="GroupID" type="hidden" value="@ViewData["GroupID"]" />  
<div id="Div1"> 
    <div class="5grid-layout"> 
     <div class="row"> 
      <div class="8u mobileUI-main-content"> 
       <!-- Content --> 
       <div id="content"> 
        <br /> 
        <!-- Article --> 
        <article class="featured"> 
         <header> 
          <h2>Registration</h2> 
          <span class="byline"></span> 
         </header> 
        </article> 
        <!-- Section --> 
        <div class="5grid grid-spaced"> 
         <div class="row"> 
          <section class="do-6u"> 
           <h2>Step 3.</h2> 
           <p> 
            You can add members to your group/family by selecting how the members will be notified (ex. Email, Cellphone) and the address/phone # of the member. 
           </p> 
           <p /> 
            <div id='contactsList'> 
             <table class='contactsEditor'> 
              <tbody data-bind="foreach: contacts"> 
               <tr> 
                <td> 
                 <input type="radio" value="Email" data-bind="checked: contactType" />E-mail 
                 <input type="radio" value="Voice" data-bind="checked: contactType" />Voice 
                 <input type="radio" value="SMS" data-bind="checked: contactType" />SMS 
                </td> 
                <td> 
                 <input data-bind='value: contactValue' size="40" /> 

                 <a href='#' data-bind='click: $root.removeContact'>Remove</a> 
                </td>    
               </tr> 
              </tbody> 
             </table> 
             <input type="hidden" data-bind='value: lastSavedJson' /> 
             <a href='#' data-bind='click: addContact'>Add </a> 
            </div> 
           <p /> 
           <p> 
            <button name="button" value="AddNewMember" data-bind='click: save, enable: contacts().length > 0'>Invite</button> 

            <button name="button" value="Next">Finish</button> 
           </p> 
          </section> 
         </div> 
        </div> 
       </div> 
      </div> 
     </div> 
    </div> 
</div> 
} 
    <script type="text/javascript"> 
     var initialData = [ 
     { 
      contactValue: "", 
      contactType: "" 
     } 
    ]; 

    var ContactsModel = function (contacts) { 
     var self = this; 
     self.contacts = ko.observableArray(ko.utils.arrayMap(contacts, function (contact) { 
      return { contactValue: contact.firstName, contactType: contact.contactType }; 
     })); 

     self.addContact = function() { 
      self.contacts.push({ 
       contactValue: "", 
       contactType: "" 
      }); 
     }; 

     self.removeContact = function (contact) { 
      self.contacts.remove(contact); 
     }; 

     self.save = function() { 
      self.lastSavedJson(JSON.stringify(ko.toJS(self.contacts), null, 2)); 
      var s = document.getElementById("GroupID").value 
      $.ajax({ 
       url: "/Home/Add/", 
       type: "POST", 
       data: { jsonString: JSON.stringify(ko.toJS(self.contacts)), groupID: s }, 
       success: function (result) { 
       }, 
       error: function (jqXHR, textStatus, errorThrown) { 
        var errorMessage = ''; 
        $('#message').html(jqXHR.responseText); 
       } 
      }); 

     }; 


     self.lastSavedJson = ko.observable("") 
    }; 

    ko.applyBindings(new ContactsModel(initialData)); 


</script> 

MODEL:

public class Registration3Model 
{ 
    public string GroupID { get; set; } 

    // Success Message 
    public string SuccessMessage { get; set; } 

    public string jsonString { get; set; } 
} 

public class Registration4Model 
{ 
    public string GroupID { get; set; } 

    public Group SelectedGroup { get; set; } 

    public Person Owner { get; set; } 

    public List<ContactInfo> GroupContacts { get; set; } 

    // Success Message 
    public string SuccessMessage { get; set; } 
} 

控制器:

public class HomeController : Controller 
{ 
    public class JsonCatch 
    { 
     public string groupID { get; set; } 
     public string contactType { get; set; } 
     public string contactValue { get; set; } 
    } 


    [AllowAnonymous] 
    public ActionResult Registration3(Registration3Model model) 
    { 
     ViewData["GroupID"] = model.GroupID; 
     return View("Registration3", model); 
    } 

    [HttpPost] 
    [ActionName("Add")] 
    [AllowAnonymous] 
    [AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult Add(string jsonString, string GroupID) 
    { 

    string s =GroupID; 

     List<JsonCatch> j = JsonConvert.DeserializeObject<List<JsonCatch>>(jsonString); 
     foreach (JsonCatch c in j) 
     { 
      if (s != "") 
      { 

       // for member 1 
       // 1. Add Person 
       Person p = new Person(); 
       p.LastName = ""; 
       p.FirstName = ""; 
       p.PersonID = Guid.NewGuid(); 
       p.RowKey = p.PersonID.ToString(); 
       p.PartitionKey = ""; 
       p.Image = string.Format("../../Assets/Images/People/pic{0}.png", new Random().Next(1, 12)); 
       this.GetContext().InsertPerson(p); 

       // 2. Add GroupMember 
       GroupMember gm = new GroupMember(); 
       gm.RowKey = p.RowKey.ToString(); 
       gm.PartitionKey = s; 
       gm.GroupMemberID = Guid.NewGuid(); 
       gm.TrustLevel = "Readonly"; 
       this.GetContext().InsertGroupMember(gm); 

       // 3. Add ContactInfo 
       ContactInfo ci = new ContactInfo(); 
       ci.PartitionKey = p.RowKey; 
       ci.ContactInfoID = Guid.NewGuid(); 
       ci.RowKey = ci.ContactInfoID.ToString(); 
       ci.Type = c.contactType; 
       ci.Value = c.contactValue; 
       ci.UseToNotify = true; 
       this.GetContext().InsertContactInfo(ci); 

       // 4. Add Notification 
       Notification n = new Notification(); 
       n.PartitionKey = "Invitation"; 
       n.NotificationID = Guid.NewGuid(); 
       n.RowKey = n.NotificationID.ToString(); 
       n.ContactType = c.contactType; 
       n.ContactInfoValue = c.contactValue; 
       n.NotificationType = "Invitation"; 
       n.PersonRowKey = p.RowKey; 
       n.GroupRowKey = s; 
       this.GetContext().InsertNotification(n); 
      } 
      } 
     return View("Registration4", new { GroupID = s }); 
    } 

      [AllowAnonymous] 
    public ActionResult Registration4(Registration4Model model) 
    { 
     model.SelectedGroup = this.GetContext().GetGroup(model.GroupID); 
     model.GroupContacts = model.SelectedGroup.GetContactInfoes(this.GetContext()); 
     model.Owner = model.SelectedGroup.GetOwner(this.GetContext()); 

     return View(model); 
    } 

      [HttpPost] 
    [AllowAnonymous] 
    [AcceptVerbs(HttpVerbs.Post)] 
    [ActionName("Registration3")] 
    [AcceptParameter(Name = "button", Value = "Next")] 
    public ActionResult Registration3_Next(Registration4Model model) 
    { 
     return RedirectToAction("Registration4", new { GroupID = model.GroupID }); 
    } 


    [HttpPost] 
    [AllowAnonymous] 
    [AcceptVerbs(HttpVerbs.Post)] 
    [ActionName("Registration4")] 
    [AcceptParameter(Name = "button", Value = "Continue")] 
    public ActionResult Registration4_Continue(Registration4Model model) 
    { 
     return Redirect("~/AnotherWebsite.aspx"); 
    } 

    #endregion 
} 

public class AcceptParameterAttribute : ActionMethodSelectorAttribute 
{ 
    public string Name { get; set; } 
    public string Value { get; set; } 

    public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) 
    { 
     var req = controllerContext.RequestContext.HttpContext.Request; 
     return req.Form[this.Name] == this.Value; 
    } 
} 

回答

1

的问题是,您所呼叫使用Ajax的添加方法,所以你需要使用window.location = url来更改为新视图。

你应该尝试是返回一个JsonResult用的GroupId它,在Ajax调用使用window.location成功一部分,并改变看法。

模型

var newUrl="@Url.Action("Registration","Home")"; 

话外加上这个模型

self.save = function() { 
     self.lastSavedJson(JSON.stringify(ko.toJS(self.contacts), null, 2)); 
     var s = document.getElementById("GroupID").value 
     $.ajax({ 
      url: "/Home/Add/", 
      type: "POST", 
      data: { jsonString: JSON.stringify(ko.toJS(self.contacts)), groupID: s }, 
      success: function (result) { 
Code Change -----> window.location=newUrl+"/"+result; 
      }, 
      error: function (jqXHR, textStatus, errorThrown) { 
       var errorMessage = ''; 
       $('#message').html(jqXHR.responseText); 
      } 
     }); 

    }; 

我假设控制器只返回标识内。希望它有效。

+0

感谢您的帮助,但是当我编写window.location =“Home/Registration4”时,它什么都不做。 – RClarke

+0

看看我的编辑,希望它能正常工作 – estebane97

+0

理想情况下,您会从您的服务中返回您重定向到的绝对URL,否定对'var newUrl =“@ Url.Action(”Registration“,”Home“)” – timothyclifford